我有从api获得的JSON数据,我想获得一个字段列表内的json数据。
JSON数据:
[
{
"code":"en",
"native":true,
"plurals":{
"length":2,
"forms":[
"one",
"other"
]
}
}, {
"code":"de",
"native":true,
"plurals":{
"length":2,
"forms":[
"one",
"other"
]
}
}, {
"code":"le",
"native":true,
"plurals":{
"length":2,
"forms":[
"one",
"other"
]
}
}
]
我想获取list<String>
格式的代码字段数据,如下所示:
["en","de","le"]
做这件事最简单的方法是什么?
注意:我正在使用Spring的RestTemplate来获取数据。
发布于 2018-07-16 04:02:41
使用findValues
方法提取名为“code”的所有属性的值:
ObjectMapper om = new ObjectMapper();
JsonNode tree = om.readTree(json);
List<JsonNode> code = tree.findValues("code");
在示例数据上运行它会给出结果
["en", "de", "le"]
发布于 2018-07-16 01:12:52
尝试下面的方法。
public static void main(String[] args) throws JSONException {
String jsonString = jsonResponseFromApi;
JSONObject obj= new JSONObject();
JSONObject jsonObject = obj.fromObject(jsonString);
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<jsonObject.length(); i++){
list.add(jsonObject.getJSONObject(i).getString("code"));
}
System.out.println(list);
}
}
有关更多详细信息,请参阅下面的线程How to Parse this JSON Response in JAVA
https://stackoverflow.com/questions/51348439
复制相似问题