13

I need to add a new item to an existing ObjectNode, given a key and a value. The value is specified as an Object in the method sig and should be one of the types that ObjectNode.set() accepts (String, Integer, Boolean, etc). But I can't just do myObjectNode.set(key, value); because value is just an Object and of course I get a "not applicable for the arguments (String, Object)" error.

My make-it-work solution is to create a function to check the instanceof and cast it to create a ValueNode:

private static ValueNode getValueNode(Object obj) {
  if (obj instanceof Integer) {
    return mapper.createObjectNode().numberNode((Integer)obj);
  }
  if (obj instanceof Boolean) {
    return mapper.createObjectNode().booleanNode((Boolean)obj);
  }
  //...Etc for all the types I expect
}

..and then I can use myObjectNode.set(key, getValueNode(value));

There must be a better way but I'm having trouble finding it.

I'm guessing that there is a way to use ObjectMapper but how isn't clear to me at this point. For example I can write the value out as a string but I need it as something I can set on my ObjectNode and needs to be the correct type (ie everything can't just be converted to a String).

Community
  • 1
  • 1
Chris
  • 341
  • 1
  • 5
  • 12
  • take a look at this post for how to use `JsonNodeFactory` to create an `ObjectNode`: https://stackoverflow.com/questions/11503604/how-to-create-insert-new-nodes-in-jsonnode – StvnBrkdll Oct 26 '17 at 15:54

3 Answers3

26

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"]}
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48
11

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");
Gili
  • 86,244
  • 97
  • 390
  • 689
7

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);
Alexandr Arhipov
  • 836
  • 9
  • 19