JsonMappingException:没有单字符串 constructor/factory 方法

JsonMappingException: no single-String constructor/factory method

[这不是 Can not instantiate value of type from JSON String; no single-String constructor/factory method 的副本:这是一个简单得多的 POJO 和 JSON。我的解决方案也不同。]

JSON 我想解析并创建一个 POJO 来自:

{
    "test_mode": true,
    "balance": 1005,
    "batch_id": 99,
    "cost": 1,
    "num_messages": 1,
    "message": {
        "num_parts": 1,
        "sender": "EXAMPL",
        "content": "Some text"
    },
    "receipt_url": "",
    "custom": "",
    "messages": [{
        "id": 1,
        "recipient": 911234567890
    }],
    "status": "success"
}

如果响应恰好是一个错误,它看起来像:

{
    "errors": [{
        "code": 80,
        "message": "Invalid template"
    }],
    "status": "failure"
}

这是我定义的 POJO:

@Data
@Accessors(chain = true)
public class SmsResponse {

    @JsonProperty(value = "test_mode")
    private boolean testMode;

    private int balance;

    @JsonProperty(value = "batch_id")
    private int batchId;

    private int cost;

    @JsonProperty(value = "num_messages")
    private int numMessages;

    private Message message;

    @JsonProperty(value = "receipt_url")
    private String receiptUrl;

    private String custom;

    private List<SentMessage> messages;

    private String status;

    private List<Error> errors;

    @Data
    @Accessors(chain = true)
    public static class Message {

        @JsonProperty(value = "num_parts")
        private int numParts;

        private String sender;

        private String content;
    }

    @Data
    @Accessors(chain = true)
    public static class SentMessage {

        private int id;

        private long recipient;
    }

    @Data
    @Accessors(chain = true)
    public static class Error {

        private int code;

        private String message;
    }

}

注解@Data(讲述Lombok to automatically generate getters, setters, toString() and hashCode() methods for the class) and @Accessors (tells Lombok to generate the setters in such a way that they can be chained) are from Project Lombok.

似乎是一个简单的设置,但每次我 运行:

objectMapper.convertValue(response, SmsResponse.class);

我收到错误消息:

Can not instantiate value of type [simple type, class com.example.json.SmsResponse]
from String value ... ; no single-String constructor/factory method

为什么 SmsResponse 需要一个单字符串构造函数,如果是这样,我在其中接受哪个字符串?

要使用 ObjectMapper 解析和映射 JSON 字符串,您需要使用 readValue 方法:

objectMapper.readValue(response, SmsResponse.class);