问题描述
我们在下面的JSON响应中动态获取其中包含其他对象的JSON对象之一。尝试了此处提供的一些解决方案,但每次获取“ 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"
}
}
}
}
现在尝试动态获取(1298 ..)生成对象内部的值,例如Tests2.teset21。 如果尝试
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.
import com.google.gson.JsonObject;
JsonObject jsonObjectResponse = (JsonObject) new JsonParser().parse(responseInString);
JsonObject Result = jsonObjectResponse.get("loanResult").getAsJsonObject();
SysOut(Result)//gives null
或,尝试以下操作也会给出空值
JsonElement jelement = new JsonParser().parse(responseInString);
JsonObject ResultObj = jelement.getAsJsonObject();
System.out.println("ResultObj value is: " + loanResultObj.get("tests21"));
解决方法
最后,经过多次尝试,可以理解使用Gson获取值。对于我的问题,动态来自请求的ID。使用以下代码可以解决问题:
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();