jackson 如何使用@JsonCreator和@JsonGetter反序列化JSON

1szpjjfi  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(197)

我有如下的JSON:

{
  "name":"John",
  "n_age":500
}

我有一个类Person

public class Person {
    private final String name;
    private final int age;

    @JsonCreator
    public Person(@JsonProperty("name") String name) {
        this.name = name;
        this.age = 100;
    }

    public String getName() {
        return name;
    }

    @JsonGetter("n_age")
    public int getAge() {
        return age;
    }
}

我需要对它进行反序列化和序列化,但是当我尝试反序列化这个JSON时,我得到了意外的结果。

public static void main(String... args) {
    ObjectMapper mapper = new ObjectMapper();
    Person person = mapper.readValue(args[0], Person.class);
    System.out.println(person.getAge()); // I got 500, but I expect 100.
}

为什么当我试图反序列化它时,要使用@JsonGetter注解?
当我尝试反序列化JSON时,如何禁用@JsonGetter注解?

z2acfund

z2acfund1#

如果当前使用@JsonGetter,它会将属性n_ageMap到字段age。要引用docs- * 它可以用作更通用的JsonProperty注解的替代方法(在一般情况下,这是推荐的选择)。*
要修复此行为,您需要:
1.告诉jackson忽略属性n_age,否则您将获得未标记为可忽略的未识别属性的异常-@JsonIgnoreProperties("n_age")
1.告诉jackson允许对被忽略的属性使用getter(基本上使其为只读)-@JsonIgnoreProperties(value = {"n_age"}, allowGetters = true)
最后,Person应该如下所示:

@JsonIgnoreProperties(value = {"n_age"}, allowGetters = true)
public class Person {

    private final String name;
    private final int age;

    @JsonCreator
    public Person(@JsonProperty("name") String name) {
        this.name = name;
        this.age = 100;
    }

    public String getName() {
        return name;
    }

    @JsonGetter("n_age")
    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
vq8itlhq

vq8itlhq2#

我找到了解决我问题的方法,也许这是一个糟糕的方法,但它对我来说也很有效。我在反序列化过程中忽略了n_age属性,在序列化过程中允许getter。非常感谢@Chaosfire的帮助!

@JsonIgnoreProperties({"n_age"}, allowGetters = true)
public class Person {

    private final String name;
    private final int age;

    @JsonCreator
    public Person(@JsonProperty("name") String name) {
        this.name = name;
        this.age = 100;
    }

    public String getName() {
        return name;
    }

    @JsonGetter("n_age")
    public int getAge() {
        return age;
    }
}

相关问题