java - 检查嵌套 JSON 中是否存在列
问题描述
下面是我的示例 JSON
{
"_id":{
"$oid":"1564t8re13e4ter86"
},
"object":{
"shop":"shop1",
"domain":"Divers",
"sell":[
{
"location":{
"zipCode":"58000",
"city":"NEVERS"
},
"properties":{
"description":"ddddd!!!!",
"id":"f1re67897116fre87"
},
"employee":[
{
"name":"employee1",
"id":"245975"
},
{
"name":"employee2",
"id":"458624"
}
],
"customer":{
"name":"Customer1",
"custid":"test_réf"
}
"preference":"talking"
}
]
}
}
在上面的示例中,我想知道 $.object.sell.preference 中是否存在此特定列,因为在大多数情况下它不存在导致失败。
如果有任何选项我可以设置为使用 readcontext.read($...) 时返回 null 或空白作为返回,我也很好
提前致谢
问候
解决方案
注意:我指的是java
是的,可以使用 jsonObject.has() 方法进行检查。假设您有响应变量,其中包含完整的 JSON
你可以这样进行
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONObject("object").getJSONArray("sell");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("preference")) {
// Exist
} else {
//Not Exist
}
}
推荐阅读
- botframework - 如何将我的机器人变成 MS Teams 应用程序
- android - 如何停止在 kotlin 中每次启动应用程序时收到通知?
- docker - docker-compose中服务的概念和容器的概念有什么关系?
- spring-boot - Spring Boot Test MockMvc 获取自定义标头值
- python-3.x - 由于缺少 DLL 文件,CuPy 导入失败,尽管它出现在我的目录中
- git - 如何保护大量孤立的 Git 提交?
- python - Python for Everyone 第 11 章练习 2 'float' 对象不可调用
- javascript - Mongoose 过期未设置-getIndexes 中未显示过期
- java - 为什么我会收到此错误“令牌上的语法错误”;“,{此令牌后预期”
- python - 为什么即使它与 if 缩进相同,else 也会出现语法错误?