我们必须使用响应值验证在 REST API 请求有效负载中发送的值,尝试了以下内容并能够打印 JSON 数组。如何获取请求 JSON 正文数组中的特定对象。
请求有效负载 :
{
"Testinfo":{
"abc":2,
"xyz":"2020-01-01"
},
"Details":{
"eductation":{
"test1":9,
"test2":100,
"test3":50
},
"neweductiona":{
"test1":"value",
"test2":"Draws"
}
}
}
法典:
jsonObject = (JSONObject) JSONValue.parse(request);
JSONObject Testinfo = (JSONObject) jsonObject.get("Testinfo");
JSONObject Details = (JSONObject) jsonObject.get("Details");
System.err.println("Testinfo value in the request is: " + Testinfo);
System.err.println("Details value in the request is: " + Details);
输出:
{
"abc":2,
"xyz":"2020-01-01"
},
{
"eductation":{
"test1":9,
"test2":100,
"test3":50
},
"neweductiona":{
"test1":"value",
"test2":"Draws",
}
如何获取特定值,例如"详细信息.eductation.test3">
在下面尝试
JSONArray jsonArray = (JSONArray) JSONValue.parse(request)
但收到错误为:
java.lang.ClassCastException: net.minidev.json.JSONObject cannot be cast to net.minidev.json.JSONArray
请指导。
使用 JSONPath
String json = "{rn" + " "Testinfo": {rn" + " "abc": 2,rn"
+ " "xyz": "2020-01-01"rn" + "rn" + "rn" + " },rn" + "rn" + " "Details": {rn"
+ " "eductation": {rn" + " "test1": 9,rn" + " "test2": 100,rn"
+ " "test3": 50rn" + " },rn" + " "neweductiona": {rn"
+ " "test1": "value",rn" + " "test2": "Draws",rn"
+ " "test3": 50rn" + "rn" + " }rn" + " }rn" + "}";
JsonPath js = new JsonPath(json);
System.out.println("Value is : "+js.getString("Details.eductation.test3"));
输出:
值为 : 50