JsonMappingException:没有单字符串构造函数/工厂方法

mar*_*gti 1 java json jackson2

[这不是“ 无法从JSON字符串实例化类型的值的重复项没有单字符串构造函数/工厂方法:这是简单得多的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"
}
Run Code Online (Sandbox Code Playgroud)

如果响应恰好是错误,则看起来像:

{
    "errors": [{
        "code": 80,
        "message": "Invalid template"
    }],
    "status": "failure"
}
Run Code Online (Sandbox Code Playgroud)

这是我定义的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;
    }

}
Run Code Online (Sandbox Code Playgroud)

批注@Data(告诉Lombok自动生成该类的获取器,设置器toString()hashCode()方法)和@Accessors(告诉Lombok以一种可以链接的方式生成设置器)来自Project Lombok

看起来像一个简单的设置,但是每次我运行时:

objectMapper.convertValue(response, SmsResponse.class);
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:

Can not instantiate value of type [simple type, class com.example.json.SmsResponse]
from String value ... ; no single-String constructor/factory method
Run Code Online (Sandbox Code Playgroud)

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

Pho*_*nix 5

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

objectMapper.readValue(response, SmsResponse.class);
Run Code Online (Sandbox Code Playgroud)