1

[这不是不能从 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、settertoString()hashCode()方法)和@Accessors(告诉 Lombok 以可以链接的方式生成 setter)来自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,如果需要,我在其中接受哪个字符串?

4

1 回答 1

6

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

objectMapper.readValue(response, SmsResponse.class);
于 2017-09-04T10:34:02.757 回答