从对象创建Jackson对象节点

unftdfkk  于 6个月前  发布在  其他
关注(0)|答案(3)|浏览(78)

我需要向现有的ObjectNode中添加一个新项,给定一个键和一个值,该值在方法sig中指定为Object,并且 * 应该 * 是ObjectNode.set()接受的类型之一。(StringIntegerBoolean,etc).但我不能只做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
}

字符串
然后我可以用myObjectNode.set(key, getValueNode(value));

一定有更好的办法但我找不到

我猜有一种方法可以使用ObjectMapper,但目前我还不清楚如何使用。例如I can write the value out as a string,但我需要它作为我可以在ObjectNode上设置的东西,并且需要是正确的类型(即所有内容都不能转换为String)。

vohkndzv

vohkndzv1#

使用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"]}

uxh89sit

uxh89sit2#

使用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");

字符串
这段代码创建了以下JSON结构:

{
    "name1": 1,
    "name2": "someString",
    "child": {
        "name3": 2,
        "name4": "someString"
    }
}

mkshixfv

mkshixfv3#

对于那些来这里寻求问题答案的人:“如何从Object创建JacksonObjectNode?"。
你可以这样做:

ObjectNode objectNode = objectMapper.convertValue(yourObject, ObjectNode.class);

字符串

相关问题