【问题标题】:Keeping POJO intact how to inject new field in JSON using Jackson?保持 POJO 完整如何使用 Jackson 在 JSON 中注入新字段?
【发布时间】:2021-01-09 13:05:08
【问题描述】:

我的最终目标是,我有 POJO 列表。我需要使用 Jackson 将其转换为 JSON 字符串。转换为 JSON 时。我需要再添加几个键。 为了做到这一点,我只有解决方案。如果我将 POJO 列表 转换为 ObjectNode 列表,以便我可以在 ObjectNode 中添加信息。之后我将转换为 JSON 字符串

List<dummyPOJO> dummyPOJO = getPOJO(); ObjectNode objectNode = mapper.convertValue(dummyPOJO, new TypeReference<ArrayList<ObjectNode>>(){});

此代码出现跟随错误

java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

如果有任何可用的解决方案,请告诉我。提前致谢:)

【问题讨论】:

    标签: java json serialization jackson pojo


    【解决方案1】:

    以下代码看起来不正确

    ObjectNode objectNode = mapper.convertValue(dummyPOJO, new TypeReference<List<ObjectNode>>(){});
    

    它应该失败

    Type mismatch: cannot convert from List<ObjectNode> to ObjectNode
    

    可以更新为

    List<ObjectNode> objectNodes = mapper.convertValue(dummyPOJO, new TypeReference<List<ObjectNode>>(){});
    

    在不更新 POJO 的情况下,要在 json 中添加额外的字段,您可以使用以下过程

    这是一个简单的 POJO,有 3 个字段 firstName、lastName 和 age

    Person.java

    package sep2020;
    
    public class Person {
        public String firstName;
        public String lastName;
        public int age;
    
        public Person() {
        }
    
        public Person(String firstName, String lastName, int age) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }
    
        public String toString() {
            return "[" + firstName + " " + lastName + " " + age + "]";
        }
    }
    

    现在将创建一些 Person 对象并将它们转换为List&lt;ObjectNode&gt; 结构。

    然后将遍历所有 ObjectNode 并在 Person ObjectNode 中添加新归档的 Sex。

    但 POJO 结构将保持不变。

    JSONListConverter.java

    package sep2020;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import com.fasterxml.jackson.databind.node.ObjectNode;
    
    public class JSONListConverter {
        public static void main(String[] args) throws IOException {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    
            // Define map which will be converted to JSON
            List<Person> personList = Stream.of(new Person("A", "B", 34),
                    new Person("C", "D", 75), new Person("E", "F", 21),
                    new Person("G", "H", 55)).collect(Collectors.toList());
    
            List<ObjectNode> objectNodes = objectMapper.convertValue(personList,
                    new TypeReference<List<ObjectNode>>() {
                    });
    
            JsonNode jsonNode = objectMapper.convertValue(objectNodes,
                    JsonNode.class);
            // Existing Json structure
            System.out.println("Existing Json:\n"
                    + objectMapper.writeValueAsString(jsonNode));
            System.out.println("\n\n");
            // Adding an extra field
            if (objectNodes != null && objectNodes.size() > 0) {
                for (ObjectNode objectNode : objectNodes) {
                    objectNode.put("Sex", "M");
                }
            }
            jsonNode = objectMapper.convertValue(objectNodes, JsonNode.class);
            // Updated Json structure
            System.out.println("Updated Json:\n"
                    + objectMapper.writeValueAsString(jsonNode));
        }
    }
    

    输出:

    Existing Json:
    
    [ {
      "firstName" : "A",
      "lastName" : "B",
      "age" : 34
    }, {
      "firstName" : "C",
      "lastName" : "D",
      "age" : 75
    }, {
      "firstName" : "E",
      "lastName" : "F",
      "age" : 21
    }, {
      "firstName" : "G",
      "lastName" : "H",
      "age" : 55
    } ]
    
    
    
    Updated Json:
    
    [ {
      "firstName" : "A",
      "lastName" : "B",
      "age" : 34,
      "Sex" : "M"
    }, {
      "firstName" : "C",
      "lastName" : "D",
      "age" : 75,
      "Sex" : "M"
    }, {
      "firstName" : "E",
      "lastName" : "F",
      "age" : 21,
      "Sex" : "M"
    }, {
      "firstName" : "G",
      "lastName" : "H",
      "age" : 55,
      "Sex" : "M"
    } ]
    

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2022-01-02
      • 2020-09-07
      • 1970-01-01
      • 2011-10-07
      • 2012-08-21
      • 2015-10-19
      • 2021-03-09
      • 2023-03-27
      相关资源
      最近更新 更多