简体   繁体   中英

Unable to parse Json Object in Java

Below is the sample code:

    import org.json.JSONArray
    import org.json.JSONObject

    JSONObject jsonObject = new JSONObject("{\"Status\":200,\"Description\":\"Success\",\"Result\":\"{\\\"Id\\\":\\\"ABCD123\\\",\\\"clientId\\\":\\\"0c34c71c\\\",\\\"status\\\":\\\"Finished\\\",\\\"message\\\":\\\"Done\\\",\\\"type\\\":\\\"registration\\\"}\"}")
    
    /* 
     here I want to do something like:
       JSONObject innerJsonObj = (JSONObject) jsonObject.get("Result");
       String id = innerJsonObj.get("clientId");
    */

On executing JSONObject innerJsonObj = (JSONObject) jsonObject.get("Result"); - it gives:

Exception in thread "main" java.lang.ClassCastException: Cannot cast object '{"Id":"ABCD123","clientId":"0c34c71c","status":"Finished","message":"Done","type":"registration"}' with class 'java.lang.String' to class 'org.json.JSONObject'

So what modification I need to do for fetching the values present in nested JsonObject( ie Result)

Your JSON:

{
    "Status": 200,
    "Description": "Success",
    "Result": "{\"Id\":\"ABCD123\",\"clientId\":\"0c34c71c\",\"status\":\"Finished\",\"message\":\"Done\",\"type\":\"registration\"}"
}

As you can see, the value of Result is a string, not a JSON object. So you'd need to create a new JSONObject from that string:

JSONObject jsonObject = new JSONObject("{\"Status\":200,\"Description\":\"Success\",\"Result\":\"{\\\"Id\\\":\\\"ABCD123\\\",\\\"clientId\\\":\\\"0c34c71c\\\",\\\"status\\\":\\\"Finished\\\",\\\"message\\\":\\\"Done\\\",\\\"type\\\":\\\"registration\\\"}\"}");

JSONObject innerJsonObj = new JSONObject(jsonObject.getString("Result"));
String id = innerJsonObj.getString("clientId");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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