Search code examples
javajsonapigroovy

API JSON response: get key value


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?


Solution

  • 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