Home > Back-end >  Parsing complex Json response in java
Parsing complex Json response in java

Time:07-24

How to parse below json response using JSONArray, JSONObject:

Sample JSON Data:

{
  "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 ?

CodePudding user response:

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

CodePudding user response:

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"
  • Related