为什么当构造函数用@JsonCreator 注释时,它的参数必须用@JsonProperty 注释? [英] Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?
本文介绍了为什么当构造函数用@JsonCreator 注释时,它的参数必须用@JsonProperty 注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Jackson 中,当您使用 @JsonCreator
注释构造函数时,您必须使用 @JsonProperty
注释其参数.所以这个构造函数
In Jackson, when you annotate a constructor with @JsonCreator
, you must annotate its arguments with @JsonProperty
. So this constructor
public Point(double x, double y) {
this.x = x;
this.y = y;
}
变成这样:
@JsonCreator
public Point(@JsonProperty("x") double x, @JsonProperty("y") double y) {
this.x = x;
this.y = y;
}
我不明白为什么有必要.你能解释一下吗?
I don't understand why it's necessary. Can you please explain?
推荐答案
Jackson 必须知道将字段从 JSON 对象传递到构造函数的顺序.在 Java 中无法使用反射访问参数名称 - 这就是您必须在注释中重复此信息的原因.
Jackson has to know in what order to pass fields from a JSON object to the constructor. It is not possible to access parameter names in Java using reflection - that's why you have to repeat this information in annotations.
这篇关于为什么当构造函数用@JsonCreator 注释时,它的参数必须用@JsonProperty 注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文