我正在编写一段代码,在这里我需要从json数组中获得一个特定的值。我的儿子如下:
{
"coord": {
"lon": 68.37,
"lat": 25.39
},
"weather": [{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}],
"base": "stations",
"main": {
"temp": 302.645,
"pressure": 1023.33,
"humidity": 48,
"temp_min": 302.645,
"temp_max": 302.645,
"sea_level": 1025.53,
"grnd_level": 1023.33
},
"wind": {
"speed": 1.81,
"deg": 54.0002
},
"clouds": {
"all": 0
},
"dt": 1479887201,
"sys": {
"message": 0.0023,
"country": "PK",
"sunrise": 1479865789,
"sunset": 1479904567
},
"id": 1176734,
"name": "Hyderabad",
"cod": 200
}我想从数组中获得id。如果有很多,我想得到第一个项目的id。
请让我知道我该怎么做。
我用来获取天气数组的代码是:
text = builder.toString();
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
});
List mainMap2 = (List) map.get("weather");
for (Object item : mainMap2) {
System.out.println("itemResult" + item.toString());
}在这里,文本是json字符串。
发布于 2016-11-23 08:40:02
下面的行应该能起作用
int id = (int)((Map)mainMap2.get(0)).get("id");您的代码可以修改如下:
text = builder.toString();
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
});
List mainMap2 = (List) map.get("weather");
//for (Object item : mainMap2) {
// System.out.println("itemResult" + item.toString());
//}
int id = (int)((Map)mainMap2.get(0)).get("id");
System.out.println(id);发布于 2016-11-23 08:30:01
在jackson中,JSON对象被转换为LinkedHashMap<String, Object>,因此只需将Object item转换为Map<String, Object>,然后获取与键id对应的值。
这样的东西:
Integer id = null;
for (Object item : mainMap2) {
Map<String, Object> mapItem = (Map<String, Object>) item;
id = (Integer) mapItem.get("id");
if (id != null) {
// We have found an Id so we print it and exit from the for loop
System.out.printf("Id=%d%n", id);
break;
}
}输出:
Id=800https://stackoverflow.com/questions/40759128
复制相似问题