0

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 ?

2
  • Also share what have you tried ? Commented Jul 15, 2022 at 7:36
  • Does this answer your question? How to parse JSON in Java Commented Jul 15, 2022 at 7:57

2 Answers 2

0

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));       
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.