简体   繁体   English

在java中解析复杂的Json响应

[英]Parsing complex Json response in java

How to parse below json response using JSONArray, JSONObject:如何使用 JSONArray、JSONObject 解析以下 json 响应:

Sample JSON Data:示例 JSON 数据:

{
  "ABC": [
    {
      "BCD": {
        "CDE": "HIJ"
      }
    }
  ]
}

I tried below solution.我尝试了以下解决方案。

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"));
}

How to parse an object inside an object of an array ?如何解析数组对象中的对象? How to get CDE ?如何获得 CDE ?

The below should work:以下应该工作:

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));       
    }
}

https://github.com/octomix/josson https://mvnrepository.com/artifact/com.octomix.josson/josson 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM