[英]Create Jackson ObjectNode from Object
I need to add a new item to an existing ObjectNode
, given a key and a value. 我需要在给定键和值的情况下向现有ObjectNode
添加新项。 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). 该值在方法sig中指定为Object
,并且应该是ObjectNode.set()接受的类型之一( String
, Integer
, Boolean
等)。 But I can't just do myObjectNode.set(key, value);
但我不能只做myObjectNode.set(key, value);
because value is just an Object
and of course I get a "not applicable for the arguments (String, Object)" error. 因为value只是一个Object
,当然我得到一个“不适用于参数(String,Object)”的错误。
My make-it-work solution is to create a function to check the instanceof
and cast it to create a ValueNode
: 我的make-it-work解决方案是创建一个函数来检查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
}
..and then I can use myObjectNode.set(key, getValueNode(value));
..然后我可以使用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. 我猜有一种方法可以使用ObjectMapper
但此时我怎么也不清楚。 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). 例如, 我可以将值写为字符串,但我需要它作为我可以在我的ObjectNode上设置的东西,并且需要是正确的类型(即一切都不能只是转换为字符串)。
Use ObjectMapper#convertValue method to covert object to a JsonNode instance. 使用ObjectMapper#convertValue方法将对象转换为JsonNode实例。 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);
}
}
Output: 输出:
{"integer":1,"string":"string","bool":true,"array":["a","b","c"]}
Using the put()
methods is a lot easier: 使用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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.