I am working on an application where I'm calling an API, retrieving the response and parsing it into a DTO. Now the response DTO I have defined is something like below,
@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ObservationsResponse {
private Integer count;
private Long retrieval_date;
private List<Observation> observations;
}
I have only defined the getters as I only need to fetch the attributes once the DTO is populated after parsing from the API response.
Coming to the question - do I need to define setters as well here so that my web client can parse the response to the DTO. Does the web client use setters to set the relevant attributes or is it done through some other mechanic (I don't think it can be done through reflections here as it is a field we are trying to access, correct me if I'm wrong).
I'm using spring web client for the API request,
webClient.get().uri(uri).retrieve()
.onStatus(httpStatus -> !HttpStatus.OK.is2xxSuccessful(), ClientResponse::createException)
.bodyToMono(ReviewPageResponse.class)
.retryWhen(Constant.RETRY_BACKOFF_SPEC)
.block();
You will have to provide a way to actually set the values.
Most codecs support the java bean convention, i.e. use the default constructor, and use setters to set the values.
For JSON, Spring WebClient uses Jackson2JsonDecoder, which also supports alternatives, but that requires some extra code.
For example if you use @JsonCreator you don't need setters:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class GenericHttpError {
@JsonCreator
public GenericHttpError(@JsonProperty("type") String type, @JsonProperty("message") String message,
@JsonProperty("causes") List<String> causes, @JsonProperty("code") int code,
@JsonProperty("details") List<Detail> details) {
this.type = type;
this.message = message;
this.causes = causes;
this.code = code;
this.details = details;
}