保持POJO结构不变,如何使用Jackson在JSON中注入新字段?

huangapple go评论85阅读模式
英文:

Keeping POJO intact how to inject new field in JSON using Jackson?

问题

我的终极目标是,我有一系列的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无法转换为com.fasterxml.jackson.databind.node.ObjectNode

如果有任何解决方案,请提前告知,谢谢!

英文:

My ultimate aim is, I have list of POJO. I need to convert as a JSON String using Jackson. While converting as JSON. I need to add few more keys.
In order to do that, I have only solution. If I convert as list of POJO into list of ObjectNode so that I can add info in ObjectNode. After that I will convert as JSON String.

List&lt;dummyPOJO&gt; dummyPOJO = getPOJO();
ObjectNode objectNode = mapper.convertValue(dummyPOJO, new TypeReference&lt;ArrayList&lt;ObjectNode&gt;&gt;(){});

This code is giving an follow error

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

Please let me know if any solution available. Thanks in Advance 保持POJO结构不变,如何使用Jackson在JSON中注入新字段?

答案1

得分: 1

以下是翻译后的内容:

以下代码似乎是不正确的:

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

它应该失败并显示:

类型不匹配无法从List<ObjectNode>转换为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<ObjectNode>结构。

然后将遍历所有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);

        // 定义要转换为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);
        // 现有的JSON结构
        System.out.println("现有的Json:\n"
                + objectMapper.writeValueAsString(jsonNode));
        System.out.println("\n\n");
        // 添加额外的字段
        if (objectNodes != null && objectNodes.size() > 0) {
            for (ObjectNode objectNode : objectNodes) {
                objectNode.put("Sex", "M");
            }
        }
        jsonNode = objectMapper.convertValue(objectNodes, JsonNode.class);
        // 更新后的JSON结构
        System.out.println("更新后的Json:\n"
                + objectMapper.writeValueAsString(jsonNode));
    }
}

输出:

现有的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
} ]



更新后的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"
} ]
英文:

The following code looks to be incorrect

ObjectNode objectNode = mapper.convertValue(dummyPOJO, new TypeReference&lt;List&lt;ObjectNode&gt;&gt;(){});

It should fail with

Type mismatch: cannot convert from List&lt;ObjectNode&gt; to ObjectNode

It could be updated to

List&lt;ObjectNode&gt; objectNodes = mapper.convertValue(dummyPOJO, new TypeReference&lt;List&lt;ObjectNode&gt;&gt;(){});

Without updating POJO, to add an extra field in json you can use following procedure

This is a simple POJO having 3 fields firstName, lastName and 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 &quot;[&quot; + firstName + &quot; &quot; + lastName + &quot; &quot; + age + &quot;]&quot;;
}
}

Now will create some Person objects and will convert them List&lt;ObjectNode&gt; structure.

Then will iterate over all ObjectNode and will add new filed Sex in the Person ObjectNode.

But POJO structure will remain unchanged.

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&lt;Person&gt; personList = Stream.of(new Person(&quot;A&quot;, &quot;B&quot;, 34),
new Person(&quot;C&quot;, &quot;D&quot;, 75), new Person(&quot;E&quot;, &quot;F&quot;, 21),
new Person(&quot;G&quot;, &quot;H&quot;, 55)).collect(Collectors.toList());
List&lt;ObjectNode&gt; objectNodes = objectMapper.convertValue(personList,
new TypeReference&lt;List&lt;ObjectNode&gt;&gt;() {
});
JsonNode jsonNode = objectMapper.convertValue(objectNodes,
JsonNode.class);
// Existing Json structure
System.out.println(&quot;Existing Json:\n&quot;
+ objectMapper.writeValueAsString(jsonNode));
System.out.println(&quot;\n\n&quot;);
// Adding an extra field
if (objectNodes != null &amp;&amp; objectNodes.size() &gt; 0) {
for (ObjectNode objectNode : objectNodes) {
objectNode.put(&quot;Sex&quot;, &quot;M&quot;);
}
}
jsonNode = objectMapper.convertValue(objectNodes, JsonNode.class);
// Updated Json structure
System.out.println(&quot;Updated Json:\n&quot;
+ objectMapper.writeValueAsString(jsonNode));
}
}

Output:

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

huangapple
  • 本文由 发表于 2020年9月23日 18:37:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64026098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定