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

时间:2018-03-27 17:13:10

标签: java json jackson pojo jackson-databind

要求:

  1. 将json文件中的选定字段收集到POJO(字段名称不匹配)
  2. 更新POJO的其他非映射字段
  3. 使用POJO字段名称转换回jsonNode
  4. 问题: 第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"}
    

1 个答案:

答案 0 :(得分:1)

解决方案是将@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反序列化。