我正在处理一个应用程序,在这个应用程序中,我调用API,检索响应并将其解析为DTO。现在我定义的响应DTO如下所示,
@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ObservationsResponse {
private Integer count;
private Long retrieval_date;
private List<Observation> observations;
}
我只定义了getter,因为我只需要在从API响应解析后填充DTO后获取属性。
接下来的问题是,我是否需要在这里也定义setter,以便我的web客户端可以解析对DTO的响应?web客户端是否使用setter来设置相关属性,或者是通过其他机制来完成(我不认为它可以通过这里的反射来完成,因为它是我们试图访问的一个领域,如果我错了,请纠正我)。我正在使用spring web客户端API请求,
webClient.get().uri(uri).retrieve()
.onStatus(httpStatus -> !HttpStatus.OK.is2xxSuccessful(), ClientResponse::createException)
.bodyToMono(ReviewPageResponse.class)
.retryWhen(Constant.RETRY_BACKOFF_SPEC)
.block();
您必须提供一种实际设置值的方法。
大多数编解码器支持java bean约定,即使用默认构造函数,并使用setter来设置值。
对于JSON, Spring WebClient使用Jackson2JsonDecoder,它也支持其他选项,但是需要一些额外的代码。
例如,如果你使用@JsonCreator,你不需要setter:
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;
}