【问题标题】:JSON parse error: Cannot construct instance of `com.dto.IdDTO` (although at least one Creator exists)JSON 解析错误:无法构造 `com.dto.IdDTO` 的实例(尽管至少存在一个 Creator)
【发布时间】:2020-06-14 20:35:17
【问题描述】:

我有一个使用 Azul 的 2.2.4 版和 Zulu Java 11.0.5 的 Spring Boot 应用程序。它正在访问部署在 Payara Web 服务器(版本 5.194)上的 REST Web 服务。

我正在使用以下 DTO:

public class IdDTO extends BasicResponseDTO {
    private long id;

    public IdDTO(long id) {
        this.id = id;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

}

public class BasicResponseDTO implements Serializable {

    private String errorCode;

    public BasicResponseDTO() {
        this.setErrorCode(null);
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

}

我调用了一个 REST Web 服务,我看到我从 Postman 收到(正确)以下响应:

{
    "errorCode": null,
    "id": 3534016
}

但是,当我检索响应时,出现以下异常:

class org.springframework.web.client.RestClientException/Error while extracting response for type [class com.dto.IdDTO] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.dto.IdDTO` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.dto.IdDTO` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (PushbackInputStream); line: 1, column: 2]

有没有人知道为什么应用程序无法将接收到的 JSON 映射到对象?

附: 1) 我还有其他扩展 BasicResponseDTO 的 DTO,并且反序列化对它们很好。

附: 2) 服务端和客户端的类定义是一样的。

【问题讨论】:

标签: json spring-boot rest java-11 payara


【解决方案1】:

IdDTO 上没有默认构造函数。只有一个带id的:

public IdDTO(long id) {
    this.id = id;
}

你必须添加一个:

public IdDTO() {
}

这是 JSON 反序列化从您的类构造对象所需要的

【讨论】:

  • 谢谢!!我花了几个小时调试这个。
【解决方案2】:

这里已经回答了这个问题:JSON parse error: Can not construct instance of io.starter.topic.Topic

在一般设计方面,我强烈建议使用第二个解决方案来注释构造函数,而不是默认参数构造函数。这样您就可以拥有不可变字段(将它们设为final)并确保您不接受空值。在 2020 年,由于序列化遗留设计,我会考虑使用默认构造函数的任何设计。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 2019-07-28
    • 2019-06-01
    • 2021-01-30
    • 2018-01-17
    • 2019-04-01
    • 2018-07-05
    • 2022-12-12
    相关资源
    最近更新 更多