[英]Jackson deserialization circumventing final fields
这是代码
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.ToString;
public class Main {
public static void main(String[] args) throws Exception {
Fields f1 = new Fields(1);
System.out.println(f1);
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(f1);
System.out.println(str);
Fields f2 = mapper.readValue(str, Fields.class);
System.out.println(f2);
}
@Data
@ToString
public static class Fields {
private final long value1;
private final long value2;
public Fields(@JsonProperty("blah") long value) {
this.value1 = value++;
this.value2 = value++;
System.out.println(this);
}
}
}
产量
Main.Fields(value1=1, value2=2)
Main.Fields(value1=1, value2=2)
{"value1":1,"value2":2}
Main.Fields(value1=0, value2=1)
Main.Fields(value1=1, value2=2)
我的问题是:
谢谢
为什么我需要用@JsonProperty注释构造函数?
不是。 需要的是一个可访问的构造函数。 您可以拥有无参数构造函数
public Fields() {
this.value1 = 0;
this.value2 = 0;
System.out.println("cons: " + this);
}
(必须初始化字段,因为它们是final
)或者你可以有一个Jackson将根据声明的@JsonProperty
名称尝试解析的构造函数。 请注意,默认情况下, JsonProperty#required
为false
。
为什么jackson在完成构建后修改了没有setter的私有final字段? 如果是这样,我该如何关闭它?
因为它可以。 因此,它允许您使用反序列化的不可变类型。 我知道没有内置的方法可以禁用此功能。
为什么jackson在完成构建后修改了没有setter的私有final字段? 如果是这样,我该如何关闭它?
在配置映射器时,可以将MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS
属性设置为false
(默认情况下为true
)。
例:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Temp {
private static final String RAW = "{\"value1\": \"aabbcc\",\"value2\":\"zzzzz\"}";
public static void main(String[] args) throws Exception {
System.out.println(new ObjectMapper().readValue(RAW, TestClass.class));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // you will receive UnrecognizedPropertyException without this line
mapper.configure(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS, false);
System.out.println(mapper.readValue(RAW, TestClass.class));
}
public static class TestClass {
private final String value1;
private final String value2;
@JsonCreator
public static TestClass createTestClass(
@JsonProperty("value1") String value1,
@JsonProperty("blah") String value2) {
return new TestClass(value1, value2);
}
private TestClass(String value1, String value2) {
this.value1 = value1;
this.value2 = value2;
}
public String getValue1() {
return value1;
}
public String getValue2() {
return value2;
}
@Override
public String toString() {
return "TestClass{" + "value1=" + value1 + ", value2=" + value2 + '}';
}
}
}
输出:
TestClass{value1=aabbcc, value2=zzzzz}
TestClass{value1=aabbcc, value2=null}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.