使用 json 保存和加载数据需要 json 的构造函数来加载对象,并且我在使用 lombok 注释时遇到问题。我应该怎么办?
这是我的类在尝试使用注释构建我的项目之前和之后的样子:
@Data
public class Item { //before
private int id;
private int amount;
public Item(@JsonProperty("id") int id, @JsonProperty("amount") int amount) {
this.id = id;
this.amount = amount;
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor //I don't want this here as it could cause complications in other places. But json requires I have this...
public class Item { //after
private int id;
private int amount;
}
我不想使用 lombok 的 NoArgsConstructor 注释,因为我不想为此类使用无参数构造函数。我意识到我可以这样做:
private Item() {
}
但希望有更好的方法...
从 lombok 1.18.4 开始,您可以配置将哪些注释复制到构造函数参数。将其插入到您的lombok.config
:
lombok.copyableAnnotations += com.fasterxml.jackson.annotation.JsonProperty
然后只需添加@JsonProperty
到你的领域:
@Data
@AllArgsConstructor
public class Item {
@JsonProperty("id")
private int id;
@JsonProperty("amount")
private int amount;
}
尽管注释参数可能看起来不必要,但实际上它们是必需的,因为在运行时构造函数参数的名称不可用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)