gpt4 book ai didi

java - 使用 POJO 字段名将 POJO 转换为 JsonNode

转载 作者:行者123 更新时间:2023-12-02 11:27:20 26 4
gpt4 key购买 nike

要求:

  1. 将 json 文件中选定的字段收集到 POJO 中(字段名称不匹配)
  2. 更新 POJO 的其他非映射字段
  3. 转换回带有 POJO 字段名的 jsonNode

问题:步骤 1 和 2 没问题。当将 POJO 转换回 JsonNode 时,我无法在 POJO 字段名称中获取它。谁能建议一种方法来实现这个?

下面是我的代码

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyPOJO {

@JsonProperty("Firstname")
private String name;

@JsonProperty("Country")
private String nationality;

private String state;

//getters and setters
}

逻辑

     ObjectMapper map = new ObjectMapper();
JsonNode root =map.readTree(new Main().getResorceFile());
List<MyPOJO> myList = new ArrayList<MyPOJO>();

for(JsonNode each : root){
MyPOJO myPOJO = new MyPOJO();
myPOJO= map.readValue(each.toString(),MyPOJO.class);
System.out.println(myPOJO.toString());
myList.add(myPOJO);
}
for(MyPOJO p : myList){
JsonNode node = map.convertValue(p,JsonNode.class);
System.out.println((node.toString()));
}

Json 文件

    {
{
"Firstname":"Tez",
"Lastname":"Morris",
"Country":"US"
},
{
"Firstname":"Kip",
"Lastname":"Lee",
"Country":"US"
},
{
"Firstname":"Pam",
"Lastname":"Carr",
"Country":"US"
},
{
"Firstname":"lin",
"Lastname":"Dale",
"Country":"US"
}
}

输出:

    Main{name='Tez', nationality='US', state='null'}
Main{name='Kip', nationality='US', state='null'}
Main{name='Pam', nationality='US', state='null'}
Main{name='lin', nationality='US', state='null'}
{"state":null,"Firstname":"Tez","Country":"US"}
{"state":null,"Firstname":"Kip","Country":"US"}
{"state":null,"Firstname":"Pam","Country":"US"}
{"state":null,"Firstname":"lin","Country":"US"}

预期输出

    Main{name='Tez', nationality='US', state='null'}
Main{name='Kip', nationality='US', state='null'}
Main{name='Pam', nationality='US', state='null'}
Main{name='lin', nationality='US', state='null'}
{"state":null,"name":"Tez","nationality":"US"}
{"state":null,"name":"Kip","nationality":"US"}
{"state":null,"name":"Pam","nationality":"US"}
{"state":null,"name":"lin","nationality":"US"}

最佳答案

解决方案是将 @JsonProperty 放在具有不同值的 getter 和 setter 上,例如:

[…]
private String nationality;

@JsonProperty("nationality")
public String getNationality() {
return nationality;
}

@JsonProperty("Country")
public void setNationality(String nationality) {
this.nationality = nationality;
}
[…]

getter 执行序列化,setter 执行反序列化。

关于java - 使用 POJO 字段名将 POJO 转换为 JsonNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com