我在这里要做的是在从API调用获得的Json对象中进行迭代,以搜索与键相关的值。但是,我无法从每次迭代中获取元组。从以下代码中:
public void findResponseValue(String param, String inputValue){
ArrayList<String> jsonArray = response.getBody().jsonPath().get("");
Iterator<String> iterator = jsonArray.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
iterator.next();
}
我收到以下错误
java.lang.ClassCastException:无法将类java.util.HashMap强制转换为类java.lang.String(java.util.HashMap和java.lang.String在加载程序'bootstrap'的模块java.base中) / p>
它可以正确地遍历arrayList,但是无法从中获取值。
响应正文示例
[
{
"creationDate": "2017-05-29T07:45:43Z",
"createdBy": "YYY.YYY",
"lastUpdate": "2018-09-26T10:10:12Z",
"updatedBy": "XXX.XXX",
"id": 22,
"partner": "ALS",
"countries": [
],
"countriesCodes": "NL",
"salesChannels": [
{
"code": "Integrated"
}
],
"touchPoints": [
],
"serviceEntity": "AWPNL",
"flag": false,
"activated": true,
"type": "dcx"
},
{
"creationDate": "2017-06-01T13:22:29Z",
"createdBy": "YYY.YYY",
"lastUpdate": "2017-11-30T12:24:36Z",
"updatedBy": "MMM.T.NNN",
"id": 39,
"partner": "ALS",
"countries": [
],
"countriesCodes": "ES",
"salesChannels": [
{
"code": "Integrated"
}
],
"touchPoints": [
],
"serviceEntity": "AWPES",
"flag": false,
"activated": true,
"type": "dcx"
}
]
答案 0 :(得分:0)
您的回复正文应如下:
{"data":[
{
"creationDate": "2017-05-29T07:45:43Z",
"createdBy": "YYY.YYY",
"lastUpdate": "2018-09-26T10:10:12Z",
"updatedBy": "XXX.XXX",
"id": 22,
"partner": "ALS",
"countries": [
],
"countriesCodes": "NL",
"salesChannels": [
{
"code": "Integrated"
}
],
"touchPoints": [
],
"serviceEntity": "AWPNL",
"flag": false,
"activated": true,
"type": "dcx"
},
{
"creationDate": "2017-06-01T13:22:29Z",
"createdBy": "YYY.YYY",
"lastUpdate": "2017-11-30T12:24:36Z",
"updatedBy": "MMM.T.NNN",
"id": 39,
"partner": "ALS",
"countries": [
],
"countriesCodes": "ES",
"salesChannels": [
{
"code": "Integrated"
}
],
"touchPoints": [
],
"serviceEntity": "AWPES",
"flag": false,
"activated": true,
"type": "dcx"
}
]}
这是我使用的一种方法(使用了Gson解析器API)。 在for循环中,您可以比较您的键或值。
public static void findResponseValue(String param, String inputValue){
JsonObject jsonObject = new JsonParser().parse(jsonResponseBody).getAsJsonObject();
JsonElement jsonElement = jsonObject.get("data");
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
System.out.println(i+". Array element Content:"+jsonArray.get(i));
JsonObject jsonObj = jsonArray.get(i).getAsJsonObject();
System.out.println("\t creationDate:"+jsonObj.get("creationDate")+" partner:"+jsonObj.get("partner"));
}
}