使用 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;
}
尽管注解参数看似不必要,但实际上是必需的,因为在运行时构造函数参数的名称不可用。
关于java - 绕过 Json jackson 和 lombok 构造函数要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55321791/