Getting around Json jackson and lombok constructor requirements

别说谁变了你拦得住时间么 提交于 2019-12-08 03:59:32

try adding this to your lombok config file:

lombok.anyConstructor.addConstructorProperties=true
config.stopBubbling = true

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

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.

So what you're saying is that Jackson requires no-args constructor for deserialization, and you don't want to add no-args constructors to your classes because that doesn't play well with your model.

Lombok is completely irrelevant here - it makes zero difference whether no-args constructor would be written manually or generated by Lombok, it'll still be just a no-args constructor.

Your real question is - can I make Jackson work without no-argument constructors on target classes. There are multiple answers to that already, you have almost done it. Here's what has to be done:

  1. Add @JsonCreator annotation to your constructor
  2. Add @JsonProperty("propName") to constructor parameters

You did the #2 but not #1. Add that and this should fix your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!