Java 如何在最少的场景中调用可选的方法
我有Json,它可以如下所示:Java 如何在最少的场景中调用可选的方法,java,java-8,gson,optional,Java,Java 8,Gson,Optional,我有Json,它可以如下所示: { "workshop_name" : "ABC" "user_name" : "DEF" } public static EnrichContext createEnricher(JSONObject json) { EnrichContext enrichContext = new EnrichContext(); enrichContext.setWorkshopName(Optional.ofNullable(json.g
{
"workshop_name" : "ABC"
"user_name" : "DEF"
}
public static EnrichContext createEnricher(JSONObject json) {
EnrichContext enrichContext = new EnrichContext();
enrichContext.setWorkshopName(Optional.ofNullable(json.getString("workshop_name")).orElse("DEFAULT"));
enrichContext.setUserName(json.getString("user_name"));
}
在我的应用程序中,workshop\u name
不是强制性的,因此它可以是最低版本:
{
"user_name" : "DEF"
}
现在我正在考虑使用Java8 Optional从JSON获取workshop\u name
。我正在使用org.json库和JSONObject
。我可以像这样轻松地检查可选项:
{
"workshop_name" : "ABC"
"user_name" : "DEF"
}
public static EnrichContext createEnricher(JSONObject json) {
EnrichContext enrichContext = new EnrichContext();
enrichContext.setWorkshopName(Optional.ofNullable(json.getString("workshop_name")).orElse("DEFAULT"));
enrichContext.setUserName(json.getString("user_name"));
}
我被迫切换到GSON,它看起来有点不同
json.get("workshop_name").getAsString();
这意味着我在JsonObject上调用了<代码> > <代码>(从GSON)到中间有一个新的对象。< /P> 我尝试使用嵌套可选检查,但它看起来太复杂了
我得出的结论是:enrichContext.setWorkshopName((Optional.ofNullable(json.get("workshop_name")).orElse(new JsonPrimitive("DEFAULT"))).getAsString());
我不喜欢每次读取时都创建新的
JsonPrimitive
。有没有更好的方法解决这个问题?您可以使用可选的而不是可选的
这就是我要找的!我也喜欢在这里使用方法引用。最佳的和好看的。