问题描述
我需要在给定键和值的情况下将新项添加到现有的ObjectNode
中.该值在方法sig中指定为Object
,并且应该是ObjectNode.set()接受的类型之一(String
,Integer
,Boolean
等).但是我不能只做myObjectNode.set(key, value);
,因为值只是一个Object
,当然我会得到一个不适用于参数(字符串,对象)" 错误.
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.
我的工作解决方案是创建一个函数来检查instanceof
并将其强制转换为创建ValueNode
:
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
}
..然后我可以使用myObjectNode.set(key, getValueNode(value));
..and then I can use myObjectNode.set(key, getValueNode(value));
必须有更好的方法,但我很难找到它.
There must be a better way but I'm having trouble finding it.
我猜想有一种使用ObjectMapper
的方法,但是目前我还不清楚.例如我可以将值写为字符串,但我需要它是我可以在ObjectNode上设置的东西,并且必须是正确的类型(即,不能将所有内容都转换为String).
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).
推荐答案
使用 ObjectMapper#convertValue 方法可将对象隐藏到JsonNode实例.这是一个示例:
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);
}
}
输出:
{"integer":1,"string":"string","bool":true,"array":["a","b","c"]}
这篇关于从对象创建Jackson对象节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!