首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用jackson从json数组中检索值

使用jackson从json数组中检索值
EN

Stack Overflow用户
提问于 2016-11-23 08:14:33
回答 2查看 9.6K关注 0票数 3

我正在编写一段代码,在这里我需要从json数组中获得一个特定的值。我的儿子如下:

代码语言:javascript
运行
复制
{
  "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。

请让我知道我该怎么做。

我用来获取天气数组的代码是:

代码语言:javascript
运行
复制
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字符串。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-11-23 08:40:02

下面的行应该能起作用

代码语言:javascript
运行
复制
int id = (int)((Map)mainMap2.get(0)).get("id");

您的代码可以修改如下:

代码语言:javascript
运行
复制
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);
票数 3
EN

Stack Overflow用户

发布于 2016-11-23 08:30:01

在jackson中,JSON对象被转换为LinkedHashMap<String, Object>,因此只需将Object item转换为Map<String, Object>,然后获取与键id对应的值。

这样的东西:

代码语言:javascript
运行
复制
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;
    }
}

输出:

代码语言:javascript
运行
复制
Id=800
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40759128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档