如何使用Jackson读取单个JSON字段 [英] How to read single JSON field with Jackson

查看:696
本文介绍了如何使用Jackson读取单个JSON字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当大的JSON响应,我对单个字段感兴趣-status:

{
  "title": "Some title",
  "status": "pending",
  "data": {
    ...
  },
  "meta": {
    ...
  }
}

我需要做的只是读取JSON响应的status值作为字符串.我希望不必构建POJO对其进行建模,因为在我的应用程序中,我只需要将JSON以特定状态存储在数据库中或将其丢弃.

该应用程序已经在其他更复杂的情况下使用Jackson,因此我更喜欢使用该库.到目前为止,我发现的所有示例都尝试将JSON映射到对象.

解决方案

如果所需字段是非空文本字段,则在对象足够小以适合主内存,检索其值的简单方法是使用类似

的方法

  public static String readField(String json, String name) throws IOException {
    if (field != null) {
      ObjectNode object = new ObjectMapper().readValue(json, ObjectNode.class);
      JsonNode node = object.get(name);
      return (node == null ? null : node.textValue());
    }
    return null;
  }

ObjectNode是通用 Jackson 类,而不是POJO类.如果要使用多个值,则应将ObjectMapper缓存(甚至是线程安全的).

运行

System.out.println(readField(response, "status"));

使用上面的JSON响应字符串,返回

pending

符合预期.在StackOverflow中的其他地方中可以找到类似的解决方案. >

对于非常大的JSON对象(例如存储在文件中的JSON对象),应使用Jackson的流式传输方法,如其他答案所建议.

I have a fairly large JSON response in which I'm interested in single field - status:

{
  "title": "Some title",
  "status": "pending",
  "data": {
    ...
  },
  "meta": {
    ...
  }
}

All I need to do is read the status value of the JSON response as string. I would prefer to not have to build a POJO to model it, because in my application I just need to store the JSON in a database on a particular status or discard it.

The application already uses Jackson for other more complicated cases so I'd prefer to stick with that library. So far all the examples I've found try to map the JSON to an object.

解决方案

If the field required is a non-null text field, at the "first level" of the hierarchy (i.e., not any nested object) of a JSON object small enough to fit in main memory, a simple way of retrieving its value is using a method like

  public static String readField(String json, String name) throws IOException {
    if (field != null) {
      ObjectNode object = new ObjectMapper().readValue(json, ObjectNode.class);
      JsonNode node = object.get(name);
      return (node == null ? null : node.textValue());
    }
    return null;
  }

ObjectNode is a generic Jackson class, not a POJO. If multiple values are to be used, the ObjectMapper should be cached (it is even thread-safe).

Running

System.out.println(readField(response, "status"));

using the JSON response string above, returns

pending

as expected. A similar solution can be found elsewhere in StackOverflow.

For very large JSON objects (e.g., stored in files), the streaming approach of Jackson should be used, as suggested in other answers.

这篇关于如何使用Jackson读取单个JSON字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆