I'd love to use this:
@Getter
@ToString
@RequiredArgsConstructor(onConstructor_ = {@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)})
private static class RestErrorObject {
private final String error; // optional
private final String message; // optional
private final String path; // optional
private final String status; // optional
private final String timestamp; // optional
}
But instead, I have to use this:
@Getter
@ToString
private static class RestErrorObject {
private final String error; // optional
private final String message; // optional
private final String path; // optional
private final String status; // optional
private final String timestamp; // optional
@JsonCreator
RestErrorObject(@JsonProperty("error") String error, @JsonProperty("message") String message,
@JsonProperty("path") String path, @JsonProperty("status") String status,
@JsonProperty("timestamp") String timestamp) {
this.error = error;
this.message = message;
this.path = path;
this.status = status;
this.timestamp = timestamp;
}
}
Is there any way I can use Lombok's RequiredArgsConstructor annotation with Jackson's JsonCreator? The problem appears to be the age-old Jackson requirement that each parameter in a multi-arg constructor be annotated with @JsonProperty. I understand this is a Java thing (or at least a Java 8 thing) that Jackson can't determine the argument names via reflection so the annotations must exist so Jackson knows where to pass each field from the json into the constructor. It just seems sadly redundant.
I had the same issue that you, found the solution here https://projectlombok.org/features/constructor
To put annotations on the generated constructor, you can use onConstructor=@__({@AnnotationsHere}), but be careful; this is an experimental feature. For more details see the documentation on the onX feature.
@Getter
@ToString
@RequiredArgsConstructor(onConstructor=@__(@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)))
private static class RestErrorObject {
private final String error; // optional
private final String message; // optional
private final String path; // optional
private final String status; // optional
private final String timestamp; // optional
}
Even that I found no reference to this @__(...)
, I assume it converts the annotation to a constant for the compiler.