【问题标题】:Is a Setter required in a DTO for parsing an API JSON response through Spring web client?DTO 中是否需要 Setter 来通过 Spring Web 客户端解析 API JSON 响应?
【发布时间】:2021-04-24 16:19:13
【问题描述】:

我正在开发一个调用 API、检索响应并将其解析为 DTO 的应用程序。现在我定义的响应 DTO 如下所示,

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ObservationsResponse {
    private Integer count;
    private Long retrieval_date;
    private List<Observation> observations;
}

我只定义了 getter,因为我只需要在从 API 响应解析后填充 DTO 后获取属性。

提出问题 - 我是否还需要在此处定义设置器,以便我的 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();

【问题讨论】:

  • 您需要设置器或需要指定明确的构造函数供 Jackson 使用。否则不会设置任何内容。

标签: java spring spring-boot spring-webflux spring-webclient


【解决方案1】:

您必须提供一种实际设置值的方法。

大多数编解码器都支持 java bean 约定,即使用默认构造函数,并使用 setter 设置值。

对于 JSON,Spring WebClient 使用 Jackson2JsonDecoder,它也支持替代方案,但这需要一些额外的代码。

例如,如果您使用@JsonCreator,则不需要设置器:

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;
  }

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 2015-06-08
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多