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).
Write JsonNode to JSONObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = readJsonIntoJsonNode(); String json = objectMapper. writeValueAsString(jsonNode); The readJsonIntoJsonNode() method is just a method I have created which parses a JSON string into a JsonNode - just so we have a JsonNode to write.
JsonNode is a base class that ObjectNode and ArrayNode extend. JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.
ObjectNode is a concrete implementation of JsonNode that maps a JSON object, and a JSON object is defined as following: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).
A ObjectNode provides a node for a linked list with Object data in each node.
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"]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With