显示从json响应中检索到的所有内容

时间:2017-04-21 17:54:24

标签: java json spring rest

我有使用JSON响应的端点。我可以在JSON端点中调用数组的length属性的长度数。这是我用来使用JSON响应的代码片段:

restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
Data[] response = restTemplate.getForObject("url",  Data[].class);

Integer response2 = response.length;

for(int i=0; i < response.length; i++)
{
    //retrieve all the contents of the json response here
}

EDITTED:

这是这种格式

[{"id":1,"state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi",
"state_data":"hi","state_data":"hi","state_data":"hi"},

我的挑战是如何将JSON数组中的所有内容检索为字段。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

这在很大程度上取决于JSON响应中的内容,这是一个例子。

如果这是您得到的回复:

{"result": [ {"key":"value1"}, {"key":"value2"} ] }

以下代码将打印出value1,value2。

JSONObject jsonObj = new JSONObject(response.getBody());

JSONArray result = jsonObj.getJSONArray("result");

for(int n = 0; n < result.length(); n++) {
    JSONObject item = result.getJSONObject(n);
    System.out.println(item.getString("key"));
}

答案 1 :(得分:0)

Errr,根据提供的代码量判断,您希望迭代数组,如下所示:

{
    "to" : "<device_id>",
    "data" : {
        "customKey1" : "value1",
        "customKey2" : "value2",
        "customKey3" : "value3",
    }
}