[这不是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自动生成类的getter,setters,toString()
和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
的单字符串构造函数,如果是,我接受哪个字符串?
答案 0 :(得分:5)
要使用 ObjectMapper 解析和映射JSON字符串,您需要使用readValue
方法:
objectMapper.readValue(response, SmsResponse.class);