如何在Jackson JSON中从ObjectMapper直接写入JSON对象(ObjectNode)? [英] How to directly write to a JSON object (ObjectNode) from ObjectMapper in Jackson JSON?

查看:1253
本文介绍了如何在Jackson JSON中从ObjectMapper直接写入JSON对象(ObjectNode)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试输出到Jackson JSON中的JSON对象.但是,我无法使用以下代码获取JSON对象.

I'm trying to output to a JSON object in Jackson JSON. However, I couldn't get the JSON object using the following code.

public class MyClass {

        private ObjectNode jsonObj;

        public ObjectNode getJson() {
              ObjectMapper mapper = new ObjectMapper();
              // some code to generate the Object user...
              mapper.writeValue(new File("result.json"), user);
              jsonObj = mapper.createObjectNode();
              return jsonObj;
        }

}

程序运行后,文件result.json包含正确的JSON数据.但是,jsonObj为空(jsonObj={}).我查找了 ObjectMapper 的Javadoc,但找不到写入ObjectNode(Jackson中的JSON对象)的一种简单方法. ObjectMapper中没有像下面这样的方法:

After the program runs, the file result.json contains the correct JSON data. However, jsonObj is empty (jsonObj={}). I looked up the Javadoc of ObjectMapper but couldn't find an easy way to write to a ObjectNode (JSON object in Jackson). There is no method in ObjectMapper like the following:

public void writeValue(ObjectNode json, Object value)

如何直接从ObjectMapper写入ObjectNode?

推荐答案

您需要使用

You need to make use of ObjectMapper#valueToTree() instead.

这将构造等效的JSON树表示形式.功能与将值序列化为JSON并将JSON解析为树一样,但效率更高.

This will construct equivalent JSON Tree representation. Functionally same as if serializing value into JSON and parsing JSON as tree, but more efficient.

如果不需要,您无需将User对象写出到JSON文件中.

You don't need to write the User object out to a JSON file, if that's not required.

public class MyClass {

    private ObjectNode jsonObj;

    public ObjectNode getJson() {
      ObjectMapper mapper = new ObjectMapper();
      // some code to generate the Object user...
      JsonNode jsonNode = mapper.valueToTree(user);
      if (jsonNode.isObject()) {
        jsonObj = (ObjectNode) jsonNode;
        return jsonObj;
      }
      return null;
    }
}

这篇关于如何在Jackson JSON中从ObjectMapper直接写入JSON对象(ObjectNode)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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