如何在 Json 中找到任何级别的 JsonElement



我想阅读可以出现在Json结构任何级别的"messages"元素。示例 JSON

{
"Order": {
"array": [
{
"messages": "value"
},{
"element1":"value",
"element2":"value"
}
],
"Object1":"value",
"Object2":{
"element1":"value",
"messages":"value"
}
}
}

有人可以建议我如何在 java 中阅读消息部分。在这里,这个特定的元素可以来自 json 中的级别或任何对象。

您可以使用 JSONObject 玩任何关卡,但您应该知道关卡的元素键。

import  org.json.JSONObject
JSONObject jsonObj = new JSONObject( "{"extensions":{"car":{"color":"blue","ageInYears":10},"favoriteNumber":3.14159265359,"isLucky":true}}");
jsonObj.put("child1Key1", "someValue");
JSONArray jsonArray = new JSONArray();
System.out.println("jsonObj"+jsonObj);
jsonObj.remove("child1Key1" );

System.out.println("after adding jsonObj"+jsonObj);

jsonObj
.getJSONObject("extensions")
.getJSONObject("car").put("ageInYears","100");
System.out.println("after update jsonObj"+jsonObj);

System.out.println("after remove  "+jsonObj
.getJSONObject("extensions")
.getJSONObject("car").remove("ageInYears"));;
System.out.println("after remove jsonObj"+jsonObj);

System.out.println("after remove  "+jsonObj
.getJSONObject("extensions").remove("isLucky"));
//.getJSONObject("car").remove("ageInYears"));;

System.out.println("after remove-1 jsonObj"+jsonObj);

相关内容

最新更新