我有如下的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注解?
2条答案
按热度按时间z2acfund1#
如果当前使用
@JsonGetter
,它会将属性n_age
Map到字段age
。要引用docs- * 它可以用作更通用的JsonProperty注解的替代方法(在一般情况下,这是推荐的选择)。*要修复此行为,您需要:
1.告诉jackson忽略属性
n_age
,否则您将获得未标记为可忽略的未识别属性的异常-@JsonIgnoreProperties("n_age")
。1.告诉jackson允许对被忽略的属性使用getter(基本上使其为只读)-
@JsonIgnoreProperties(value = {"n_age"}, allowGetters = true)
最后,
Person
应该如下所示:vq8itlhq2#
我找到了解决我问题的方法,也许这是一个糟糕的方法,但它对我来说也很有效。我在反序列化过程中忽略了
n_age
属性,在序列化过程中允许getter。非常感谢@Chaosfire的帮助!