Search code examples
gsonpojojsonpathjsonparserrest-assured-jsonpath

Fetch the JSONobject value to a variable which is inside the dynamically generated JSONobject


We have below JSON response which has dynamically getting one of the JSONobject which has other objects inside. Tried some of the solutions provided here, but unable to get the values, every time getting 'null'.

{
  "Result": {
    "12987654": {//this value 1298.. is dynamically getting generated at every response.
      "Tests1": {
        "test1": -0.85,
        "test2": 0.016,
        "tests3": "FAIL"
      },
      "Tests2": {
        "test21": "PASS",
        "test22": "PASS",
        "test23": "FAIL"
      }
    }
  }
}

Now Trying to get value of inside this dynamically (1298..) generating object, like Tests2.teset21. If tried as

JSONPath js.get("Results.1298.Tests1.test1")//able to get the value. however here 1298 is hardcoded and this value changes in the next run.

If tried as below, getting value as null.

import com.google.gson.JsonObject;

JsonObject jsonObjectResponse = (JsonObject) new JsonParser().parse(responseInString);
JsonObject Result = jsonObjectResponse.get("loanResult").getAsJsonObject();
SysOut(Result)//gives null

OR, trying below also gives null

JsonElement jelement = new JsonParser().parse(responseInString);
         JsonObject  ResultObj = jelement.getAsJsonObject();
         System.out.println("ResultObj  value is: " + loanResultObj.get("tests21"));

Please guide how to get value inside of dynamically generating Jsonobject.


Solution

  • Finally after many attempts, could understand using Gson to get the value. For my issue, the id which dynamic goes from Request. With below code could solve issue:

    Gson gsonResp = new Gson();
            String responseInString = response.asString();
            JsonObject jsonObjectNewResponse = gsonResp.fromJson(responseInString, JsonObject.class);
    String test12 = jsonObjectNewResponse.getAsJsonObject("Result").getAsJsonObject(<dynamicID which is been extracted from Req in the form of String>).            getAsJsonObject("test1").get("test12").getAsString();