使用 Jackson 从 json 对象列表中获取字段列表
get field list from json object list with Jackson
我有 JSON 从 api 获取的数据,我想获取 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 来获取数据。
试试下面的方法。
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
使用findValues
方法提取名为"code":
的所有属性的值
ObjectMapper om = new ObjectMapper();
JsonNode tree = om.readTree(json);
List<JsonNode> code = tree.findValues("code");
运行 它在您的示例数据上给出了结果
["en", "de", "le"]
我有 JSON 从 api 获取的数据,我想获取 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 来获取数据。
试试下面的方法。
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
使用findValues
方法提取名为"code":
ObjectMapper om = new ObjectMapper();
JsonNode tree = om.readTree(json);
List<JsonNode> code = tree.findValues("code");
运行 它在您的示例数据上给出了结果
["en", "de", "le"]