Jackson和Lombok构造函数要求

Jackson和Lombok构造函数要求

本文介绍了解决Json Jackson和Lombok构造函数要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用json保存和加载数据需要json的构造函数来加载对象,而我在获取lombok注释来与此配合使用时遇到了麻烦.我该怎么办?

Using json to save and load data requires a constructor for json to load the object, and I'm having trouble getting lombok annotations to work with this. What should I do?

这是我的类在尝试使用注释构造项目之前和之后的样子:

This is what my class looked like before and after attempting to use an annotation to construct my item:

@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注释,因为我不想为此类创建无参数的构造函数.我意识到我可以做到这一点:

I don't want to use the NoArgsConstructor annotation by lombok as I don't want a no args constructor for this class. I realise that I could do this:

private Item() {
}

但是我希望有更好的方法...

But was hoping there is a better way...

推荐答案

从lombok 1.18.4开始,您可以配置将哪些注释复制到构造函数参数中.将此插入您的lombok.config:

Since lombok 1.18.4, you can configure what annotations are copied to the constructor parameters. Insert this into your lombok.config:

lombok.copyableAnnotations += com.fasterxml.jackson.annotation.JsonProperty

然后将@JsonProperty添加到您的字段中:

Then just add @JsonProperty to your fields:

@Data
@AllArgsConstructor
public class Item {
    @JsonProperty("id")
    private int id;

    @JsonProperty("amount")
    private int amount;
}

尽管注释参数似乎不必要,但实际上是必需的,因为在运行时,构造函数参数的名称不可用.

Although the annotation parameters may seem unnecessary, they are in fact required, because at runtime the names of the constructor parameters are not available.

这篇关于解决Json Jackson和Lombok构造函数要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:32