skip to Main Content

Below is the response message (JSON) from an API endpoint.
I need to parse the JSON response, and I need to retrieve the RequestID key.

{
  "Status":1,
  "RequestID":"29d2d52c-e8fe-447f-9ee1-15e4624be58f",
  "Data":[
    {
      "RegNumber":"ASD3948506",
      "CaseData":{
        "CaseResult":{
          "Message":"success",
          "RequestID":"8C15473C0F7771F410928D5D91362B80"
        },
        "ErrorMessageList":[
        ]
      }
    }]
}

Below is my code to retrieve the RequestID[Inside the CaseResult]

JSONObject actualJson = new JSONObject(response.getResponseText())
def requestID = actualJson.get('Data[0].CaseData.CaseResult.RequestID')

When I executed it, I got the below error message.

org.json.JSONException: JSONObject["Data[0].CaseData.CaseResult.RequestID"] not found.

Could any one provide a solution for this?

3

Answers


  1. You cannot query values using that kind of string:

    'Data[0].CaseData.CaseResult.RequestID'
    

    You will get null as result

    enter image description here

    Explicit access to the values

    Using JsonSlurper you can parse any valid string json to a groovy object.

    def jsonSlurper = new JsonSlurper();
    def object = jsonSlurper.parse("{....}")
    println object
    println object.Status
    println object["Status"]
    println object["Data"][0]["CaseResult"]["RequestId"]
    

    enter image description here

    Jsonpath

    This is the only library capable to use string queries to get values from the json:

    $.Data[0].CaseData.CaseResult.RequestID
    
    String json = "...";
    String jsonPathExpression = "$.Data[0].CaseData.CaseResult.RequestID"; 
    JsonNode jsonNode = JsonPath.parse(json).read(jsonPathExpression, JsonNode.class);
    

    enter image description here

    References

    Login or Signup to reply.
  2. You can not directly query the string from json object. Use below code to get the RequestId.

    try {
      JSONObject obj = new JSONObject(json);
      String requestId = obj.getJSONArray("Data")
          .getJSONObject(0)
          .getJSONObject("CaseData")
          .getJSONObject("CaseResult")
          .getString("RequestID");
      System.out.println(requestId);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    
    Login or Signup to reply.
  3. You may try library Josson. The query syntax is the same as your expected.

    https://github.com/octomix/josson

    Josson josson = Josson.fromJsonString(response.getResponseText());
    String requestId = josson.getString("Data[0].CaseData.CaseResult.RequestID");
    System.out.println(requestId);
    // Output: 8C15473C0F7771F410928D5D91362B80
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search