Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to directly write to a JSON object (ObjectNode) from ObjectMapper in Jackson JSON?

Tags:

java

json

jackson

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;
        }

}

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)

How to write to an ObjectNode directly from ObjectMapper?

like image 843
tonga Avatar asked Aug 19 '13 18:08

tonga


1 Answers

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

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

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;
    }
}
like image 108
Ravi K Thapliyal Avatar answered Sep 27 '22 20:09

Ravi K Thapliyal