Home > Net >  Org json parsing keep getting error - is not a JSONObject
Org json parsing keep getting error - is not a JSONObject

Time:09-24

Im trying to parse id from following string json:

postResponse :{"success":true,"response_json":"{\"status\":200,\"message\":\"Success\",\"data\":{\"id\":\"f71233gg12\"}}"}

my code looks like below:

System.out.println("postResponse :" postResponse);
JSONObject responseJson = new JSONObject(postResponse);
JSONObject jsonObjectA = responseJson.getJSONObject("response_json");
JSONObject jsonObjectB = jsonObjectA.getJSONObject("data");
String the_pdf_id = jsonObjectB.get("id").toString();

i keep getting the error:

org.json.JSONException: JSONObject["response_json"] is not a JSONObject.

what could be the reason? any solution for that?

CodePudding user response:

As you can see on your data, the content at key response_json is not a an object, but only a string, another JSON-encoded string

// response_json value is a string
{"success":true,"response_json":"{\"status\":200,\"message\":\"Success\",\"data\":{\"id\":\"f71233gg12\"}}"}

// response_json value is an object
{"success":true,"response_json": {"status":200,"message":"Success","data":{"id":"f71233gg12"}}}

You need a second parse level

JSONObject jsonObjectA = new JSONObject(responseJson.getJSONString("response_json"));
  • Related