Json嵌套对象检查是否为空 [英] Json nested Objects check if null
本文介绍了Json嵌套对象检查是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下json
{
"sub1":{
"name":"Name-sub1",
"sub11":{
"name":"Name-sub11",
"sub111":{
"name":"Name-sub111",
...
},
..
},
...
},
...
}
我现在想在Java中获取内部名称Element(名称-sub111)(这是io.vertx.core.json.JsonObject)
I now want to fetch the inner name Element (Name-sub111) in java (it's a io.vertx.core.json.JsonObject)
object.getJsonObject("sub1").getJsonObject("sub11").getJsonObject("sub111").getString("name")
但是我不确定sub1还是sub11或sub111是否存在-所以我总是需要检查null
But I'm not sure if sub1 or sub11 or sub111 even exist - so I always need to check for null
if(object.getJsonObject("sub1") != null && object.getJsonObject("sub1").getJsonObject("sub11") != null && object.getJsonObject("sub1").getJsonObject("sub11").getJsonObject("sub111") != null) {
return object.getJsonObject("sub1").getJsonObject("sub11").getJsonObject("sub111").getString("name");
}
有人知道这种情况下更好的解决方案吗?
Does someone know a better solutions for this case?
推荐答案
此处的一个选项是使用Java 8 Optional,它消除了重复的方法调用.但是,对于某些人来说,最终结果可能看起来不够清晰:
an option here is to use Java 8 Optional, which eliminates the dupplicate method calls. Howewver, the end result might not look clear enough for some:
return Optional.ofNullable(object.getJsonObject("sub1")).map(subObj1 ->
Optional.ofNullable(subObj1.getJsonObject("sub11")).map(subObj11 ->
Optional.ofNullable(subObj11.getJsonObject("sub111")).map(subObj111 -> subObj111.getString("name")
)));
这篇关于Json嵌套对象检查是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文