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).