pirate_shady
pirate_shady

Reputation: 83

Java unable to parse nested json object

Below is some sample code:

import org.json.JSONObject;

String k = "{\"root1\":\"{\\\"key1\\\":\\\"val1\\\",\\\"key2\\\":1,\\\"key3\\\":null}\",\"root2\":\"OTHERS\",\"root3\":1}";
JSONObject obj = new JSONObject(str);
System.out.println(obj);

/* 
here I want to do something like:
JSONObject innerObj = (JSONObject) obj.get("root1");
String k1 = innerObj.get("key1");

Also, should work with nested inner objects, so for example, should be able to do:
String k4 = innerObj.get("key1.innerKey1");
*/
{"root1":"{\"key1\":\"val1\",\"key2\":1,\"key3\":null}","root2":"OTHERS","root3":1}

On doing JSONObject innerObj = (JSONObject) obj.get("root1"); - it gives:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject

I tried Gson, JSONParser - but still unable to do it ...

Note: Parsing of string 'k' works fine, as the obj is populated correctly and is printed out. It fails when I try to access objects within this obj: JSONObject innerObj = (JSONObject) obj.get("root1");

Upvotes: 0

Views: 989

Answers (2)

SKumar
SKumar

Reputation: 2030

There is utility StringEscapeUtils class in apache commons text library for such translations. Applying it will remove those extra double quotes around root1 value.

Add this commons-text jar dependency to your project.

Usage -

String k = "{\"root1\":\"{\\\"key1\\\":\\\"val1\\\",\\\"key2\\\":1,\\\"key3\\\":null}\",\"root2\":\"OTHERS\",\"root3\":1}";

// add this line
String unescapedJsonString = StringEscapeUtils.unescapeJson(k);

 // pass new json string to Json library
JSONObject obj = new JSONObject(unescapedJsonString);

Upvotes: 1

Shubham Pathak
Shubham Pathak

Reputation: 155

Please check this-

public static void main(String[] args) {

    String k ="{\"root1\":{\"key1\":\"val1\",\"key2\":1,\"key3\":null},\"root2\":\"OTHERS\",\"root3\":1}";
    JSONObject obj = new JSONObject(k);
    System.out.println(obj);
     
    //here I want to do something like:
    JSONObject innerObj = (JSONObject) obj.get("root1");
    Object k1 =  innerObj.get("key1");
    System.out.println(k1);
    Object k2 =  innerObj.get("key2");
    System.out.println(k2);
    Object k3 =  innerObj.get("key3");
    System.out.println(k3);
    
    System.out.println(obj.get("root2"));
    System.out.println(obj.get("root3"));
}

Output -

{"root1":{"key1":"val1","key2":1,"key3":null},"root2":"OTHERS","root3":1}
val1
1
null
OTHERS
1

Upvotes: 0

Related Questions