java - 从对象创建 Jackson ObjectNode

标签 java json jackson

我需要向现有的 ObjectNode 添加一个新项目,给定一个键和一个值。该值在方法 sig 中指定为 Object应该 是 ObjectNode.set() 接受的类型之一(StringIntegerBoolean 等)。但我不能只执行 myObjectNode.set(key, value); 因为 value 只是一个 Object 当然我得到一个 "not applicable for the参数(字符串,对象)” 错误。

我的成功解决方案是创建一个函数来检查 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 上设置的东西,并且需要是正确的类型(即不能将所有内容都转换为字符串)。

最佳答案

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

关于java - 从对象创建 Jackson ObjectNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34180538/

相关文章:

java - Spring Boot Data Rest不支持响应式?

php - 使用池的在线聊天

java - 当我使用 @JsonProperty 通过 Spring 数据从 MongoDB 检索对象时出现空字段

spring - 如何防止hibernate5在jackson序列化json对象时延迟获取?

Java - 迭代器 : "Syntax error, parameterized types are only available if source level is 5.0"

java - 如何在 Eclipse 工具提示和自动完成功能中查看外部 Java 类的参数名称?

java - 如何在主 Activity 的for循环内的线程内生成TextView

css - Bootstrap config.json - 下一步做什么?

java - 如何为 Gson 编写自定义 JSON 反序列化器?

java - 在 Spring 中编写 JSON 反序列化器或对其进行扩展的正确方法