What is the preferred way to create class that is
Preferably, I would have liked something like this to work:
@Data(onConstructor = @__(@JsonCreator))
and then have all fields to be private final
. However, this does not even compile (and I'm not sure why). Using
@AllArgsConstructor(onConstructor = @__(@JsonCreator))
will compile but only yields
InvalidDefinitionException: No serializer found for class
Lombok @Jacksonized. Using @Jacksonized annotation is the simplest solution if you are using Jackson for deserialization purposes. Just annotate the @Builder class with @Jacksonized annotation and we are good for converting the JSON string to Java object.
You definitely don't need all those @jsonProperty . Jackson mapper can be initialized to sereliazie/deserialize according to getters or private members, you of course need only the one you are using.
Overview. The @Jacksonized annotation is an add-on annotation for @Builder and @SuperBuilder . It automatically configures the generated builder class to be used by Jackson's deserialization. It only has an effect if present at a context where there is also a @Builder or a @SuperBuilder ; a warning is emitted otherwise ...
The big difference between @Value and @Data annotation is that @Value is mainly used to create immutable objects. @Value is a also an all-in-one annotation that combines: @Getter, @AllArgsConstructor, @ToString and @EqualsAndHashCode and @FieldDefaults(makeFinal = true, level = AccessLevel.
add ConstructorProperties:
lombok.config
file in an appropriate location with the line: lombok.anyConstructor.addConstructorProperties = true
@Value
annotation to your class to make it immutableThen serialization and deserialization by Jackson works as expected.
This method:
Edit: 2020-08-16
@Builder
with @Value
causes this solution to fail. (Thanks to comment from @guilherme-blanco below.) However, if you also add e.g. @AllArgsConstructor
it does still work as expected.Edit: 2021-08-19
lombok.config
file the change is not picked up unless you do a rebuild (clean then build). I have been caught out by this a few times.@Jacksonized
annotation solution is another method to achieve the desired outcome for the specific classes annotated. However, I personally prefer not to need to remember to annotate every class used for deserialization. Using lombok.config
removes this overhead.As of 15 October 2020 (Lombok v1.18.16), you should simply be able to use the @Jacksonized
annotation.
@Jacksonized @Builder @JsonIgnoreProperties(ignoreUnknown = true) public class JacksonExample { private List<Foo> foos; }
As described in the linked documentation, this annotation:
@JsonIgnoreProperties
), andbuilder().withField(field)
vs builder.field(field)
to the one configured in Lombok.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With