绕过 Json jackson 和 lombok 构造函数要求 [英] Getting around Json jackson and lombok constructor requirements

查看:43
本文介绍了绕过 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 注释,因为我不想为此类使用 no args 构造函数.我意识到我可以做到这一点:

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 构造函数要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆