我需要给一个新项添加一个ObjectNode给定的键和值。该值被指定为Object在该方法中SIG和应该是ObjectNode.set()接受(的类型之一String,Integer,Boolean等等)。但是我不能仅仅这样做,myObjectNode.set(key, value);因为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
}
Run Code Online (Sandbox Code Playgroud)
..然后我可以使用 myObjectNode.set(key, getValueNode(value));
一定有更好的方法,但是我很难找到它。
我猜想有一种使用方法,ObjectMapper但是目前我还不清楚。例如,我可以将值写为字符串,但是需要它作为我可以在ObjectNode上设置的值,并且需要正确的类型(即,不能将所有内容都转换为String)。
使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{"integer":1,"string":"string","bool":true,"array":["a","b","c"]}
Run Code Online (Sandbox Code Playgroud)
对于来这里寻找问题答案的人:“如何从 Object 创建 Jackson ObjectNode?”。
你可以这样做:
ObjectNode objectNode = objectMapper.convertValue(yourObject, ObjectNode.class);
Run Code Online (Sandbox Code Playgroud)
使用这些put()方法要容易得多:
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = mapper.createObjectNode();
root.put("name1", 1);
root.put("name2", "someString");
ObjectNode child = root.putObject("child");
child.put("name3", 2);
child.put("name4", "someString");
Run Code Online (Sandbox Code Playgroud)