【问题标题】:Create Jackson ObjectNode from Object从 Object 创建 Jackson ObjectNode
【发布时间】:2016-03-14 19:52:32
【问题描述】:

我需要给现有的ObjectNode 添加一个新项目,给定一个键和一个值。该值在方法 sig 中指定为 Object应该是 ObjectNode.set() 接受的类型之一(StringIntegerBoolean 等)。但我不能只做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 上设置的东西,并且需要是正确的类型(即不能将所有内容都转换为字符串)。

【问题讨论】:

标签: java json jackson


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      对于那些来这里回答问题的人:“如何从 Object 创建 Jackson ObjectNode?”。

      你可以这样做:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-22
        • 2017-06-02
        • 2020-07-06
        • 2016-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多