我需要向现有的 ObjectNode
添加一个新项目,给定一个键和一个值。该值在方法 sig 中指定为 Object
,应该 是 ObjectNode.set() 接受的类型之一(String
,Integer
、Boolean
等)。但我不能只执行 myObjectNode.set(key, value);
因为 value 只是一个 Object
当然我得到一个 "not applicable for the参数(字符串,对象)” 错误。
我的成功解决方案是创建一个函数来检查 instanceof
并将其转换为创建 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));
一定有更好的方法,但我找不到它。
我猜想有一种方法可以使用 ObjectMapper
但目前我还不清楚如何使用。例如I can write the value out as a string但我需要它作为我可以在我的 ObjectNode 上设置的东西,并且需要是正确的类型(即不能将所有内容都转换为字符串)。
最佳答案
使用ObjectMapper#convertValue将对象转换为 JsonNode 实例的方法。这是一个例子:
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"]}
关于java - 从对象创建 Jackson ObjectNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34180538/