提问人:Vidya B. 提问时间:7/15/2022 最后编辑:Vidya B. 更新时间:7/24/2022 访问量:104
在 java 中解析复杂的 Json 响应
Parsing complex Json response in java
问:
如何使用 JSONArray、JSONObject 解析以下 json 响应:
JSON 数据示例:
{
"ABC": [
{
"BCD": {
"CDE": "HIJ"
}
}
]
}
我尝试了以下解决方案。
JSONArray ja = new JSONArray(jsonObj.get("ABC").toString());
for(int j=0; j<ja.length(); J++)
{
JSONObject jarr = (JSONObject)ja.get(j);
System.out.print(jarr.getString("BCD"));
}
如何解析数组对象内部的对象?如何获得CDE?
答:
0赞
Bhanu
7/15/2022
#1
以下方法应该有效:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static String getCDE(String json) {
JSONObject obj = new JSONObject(json);
JSONArray abc = (JSONArray) obj.get("ABC");
JSONObject bcd = ((JSONObject) abc.get(0)).getJSONObject("BCD");
String cde = (String) bcd.get("CDE");
return cde;
}
public static void main(String[] args) {
String json = "{\r\n" +
" \"ABC\": [\r\n" +
" {\r\n" +
" \"BCD\": {\r\n" +
" \"CDE\": \"HIJ\"\r\n" +
" }\r\n" +
" }\r\n" +
" ]\r\n" +
"}";
System.out.println(getCDE(json));
}
}
0赞
Raymond Choi
7/24/2022
#2
https://github.com/octomix/josson https://mvnrepository.com/artifact/com.octomix.josson/josson
implementation 'com.octomix.josson:josson:1.3.20'
-------------------------------------------------
Josson josson = Josson.fromJsonString("{\n" +
" \"ABC\": [\n" +
" {\n" +
" \"BCD\": {\n" +
" \"CDE\": \"HIJ\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"BCD\": {\n" +
" }\n" +
" },\n" +
" {\n" +
" \"BCD\": {\n" +
" \"CDE\": \"KLM\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}");
System.out.println(josson.getNode("ABC.BCD.CDE")); // -> ["HIJ","KLM"]
System.out.println(josson.getNode("ABC[0].BCD.CDE")); // -> "HIJ"
System.out.println(josson.getNode("ABC[1].BCD.CDE")); // -> null
System.out.println(josson.getNode("ABC[2].BCD.CDE")); // -> "KLM"
System.out.println(josson.getNode("ABC.BCD.CDE[1]")); // -> "KLM"
评论