Create Jackson ObjectNode from Object

Use ObjectMapper#convertValue method to covert object to a JsonNode instance. Here is an example:

public class JacksonConvert {
    public static void main(String[] args) {
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode root = mapper.createObjectNode();
        root.set("integer", mapper.convertValue(1, JsonNode.class));
        root.set("string", mapper.convertValue("string", JsonNode.class));
        root.set("bool", mapper.convertValue(true, JsonNode.class));
        root.set("array", mapper.convertValue(Arrays.asList("a", "b", "c"), JsonNode.class));
        System.out.println(root);
    }
}

Output:

{"integer":1,"string":"string","bool":true,"array":["a","b","c"]}

For people who came here for the answer on the question: "How to create Jackson ObjectNode from Object?".

You can do it this way:

ObjectNode objectNode = objectMapper.convertValue(yourObject, ObjectNode.class);

Using the put() methods is a lot easier:

ObjectMapper mapper = new ObjectMapper();
ObjectNode root = mapper.createObjectNode();

root.put("name1", 1);
root.put("name2", "someString");

ObjectNode child = root.putObject("child");
child.put("name3", 2);
child.put("name4", "someString");

Tags:

Java

Json

Jackson