【发布时间】:2016-03-14 19:52:32
【问题描述】:
我需要给现有的ObjectNode 添加一个新项目,给定一个键和一个值。该值在方法 sig 中指定为 Object,应该是 ObjectNode.set() 接受的类型之一(String、Integer、Boolean 等)。但我不能只做myObjectNode.set(key, value);,因为值只是一个Object,当然我得到一个“不适用于参数(字符串,对象)”错误。
我的解决方案是创建一个函数来检查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 上设置的东西,并且需要是正确的类型(即不能将所有内容都转换为字符串)。
【问题讨论】:
-
看看这篇文章,了解如何使用
JsonNodeFactory创建ObjectNode:stackoverflow.com/questions/11503604/…