简体   繁体   中英

using lombok @Singular with jackson @JsonPOJOBuilder

After debugging through the jackson smile deserializer, I found that my List that was annotated with @Singular was not being found by jackson.

Is there a way to make @Singular with jackson @JsonPOJOBuilder ?

@JsonDeserialize(builder = MyClass.MyClassBuilder.class)
@Value
@Builder
@RequiredArgsConstructor
@EqualsAndHashCode
public class MyClass {

    @NonNull String name;
    @NonNull @Singular List<String> favs = new ArrayList<>();

    @JsonPOJOBuilder(withPrefix = "")
    public static final class MyClassBuilder {
    }
}

changing @Singular to @Builder.Default works just fine.

The issue here is that you initialize the favs field:

List<String> favs = new ArrayList<>();

Which due to the @Value annotation is final . Therefore it is not available to be set/overwritten by either the builder or the constructor generated by @RequiredArgsConstructor . Verify, by trying to construct an instance yourself:

MyClass.builder().name("a").fav("1").fav("2").build();

intellij here says no fav method but @Builder with @Singular should create one.
Solve by:

  1. skip the initialization of favs at field declaration and let lombok, jackson initialize
  2. create you own builder that adds elements on preexisting list

I tested with lombok 1.16.18 and jackson 2.9.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM