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

w8rqjzmb  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(309)

[这不是重复的,不能从json字符串示例化类型的值;没有单个字符串构造函数/工厂方法:这是一个简单得多的pojo和json。我的解决方案也不同。]
我要从中解析和创建pojo的json:

{
    "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自动生成getter,setter, toString() 以及 hashCode() 类的方法)和 @Accessors (告诉lombok以一种可以链接的方式生成setter)来自projectlombok。
似乎是一个简单的设置,但每次我运行:

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 ,如果是,我接受哪个字符串?

toiithl6

toiithl61#

要使用objectmapper解析和Mapjson字符串,需要使用 readValue 方法:

objectMapper.readValue(response, SmsResponse.class);

相关问题