杰克逊反序列化绕过最终领域 [英] 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)
我的问题是:
- 为什么杰克逊在构造完后不修改带有二传手的私有最终字段?如果打算这样做,如何关闭它?
- 如果jackson能够直接设置字段,为什么要求我用@JsonProperty注释构造函数? (从Fields中删除@JsonProperty会导致错误;我什至不需要使用正确的属性进行注释)
谢谢
推荐答案
为什么要求我用@JsonProperty注释构造函数?
Why is it required that I annotate the constructor with @JsonProperty?
不是.所需要的是一个可访问的构造函数.您可以有一个无参数的构造函数
It's not. What is required is an accessible constructor. You can either have a parameterless constructor
public Fields() {
this.value1 = 0;
this.value2 = 0;
System.out.println("cons: " + this);
}
(由于它们是final
,因此必须初始化这些字段),或者您可以具有一个构造函数,Jackson将根据声明的@JsonProperty
名称尝试解析该构造函数.请注意,JsonProperty#required
默认为false
.
(that necessarily initializes the fields since they are final
) or you can have a constructor that Jackson will try to resolve based on the declared @JsonProperty
name. Note that JsonProperty#required
is false
by default.
杰克逊为什么要修改没有二传手的私人决赛场 完成建设后呢?如果打算这样做,我该如何转动 关闭?
Why did jackson modify private final fields that do not have setters after finish constructing it? If this is intended, how do I turn it off?
因为可以.因此,它允许您将不可变类型与反序列化一起使用.据我所知,没有内置的方法可以禁用此功能.
Because it can. It thus allows you to use immutable types with deserialization. There is no built-in way that I know of through which you can disable this feature.
这篇关于杰克逊反序列化绕过最终领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!