简体   繁体   English

无法解析 Java 中的 Json Object

[英]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");在执行 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'线程“主”中的异常 java.lang.ClassCastException: 无法转换 object '{"Id":"ABCD123","clientId":"0c34c71c","status":"Finished","message":"Done type":"registration"}' 与 class 'java.lang.String' 到 class 'org.json.JSONObject'

So what modification I need to do for fetching the values present in nested JsonObject( ie Result)那么我需要做哪些修改来获取嵌套 JsonObject 中存在的值(即结果)

Your JSON:您的 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.如您所见, Result的值是一个字符串,而不是 JSON object。 So you'd need to create a new JSONObject from that string:因此,您需要从该字符串创建一个新的JSONObject

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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