下面是我使用 jackson 转换为 pojo 的 json 响应 -
{
paymentType": [
{
"Monthly": ["Monthly", "Monthly"],
"Prepaid": ["Prepaid", "Prepaid"]
},
""
]
}
代码:
String rspString = "{\"paymentType\": [{\"Monthly\": [\"Monthly\",\"Monthly\"],\"Prepaid\": [\"Prepaid\",\"Prepaid\"]},\"\"]}";
JsonUtil jsonUtil = new JsonUtil();
PaymentTypeResponse PaymentTypeRsp = new PaymentTypeResponse();
PaymentTypeRsp = (PaymentTypeResponse) jsonUtil.Json2Object(rspString, PaymentTypeRsp);
System.out.println(PaymentTypeRsp.getPaymentType().size());
我收到以下异常:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.test.sample.PaymentTypeRespons] from String value (''); no single-String constructor/factory method
响应中有一个空白值,在转换为pojo时如何处理这些值?
同样,如果为null,如何处理这种情况?
任何指针将不胜感激。
提前致谢。
这是类(class):
public class PaymentType
{
@JsonProperty("Monthly")
public List<String> monthly;
@JsonProperty("Prepaid")
public List<String> prepaid;
//getter and setters
}
public PaymentTypeResponse
{
@JsonProperty("paymentType")
public List<PaymentType> paymentType;
//setters and Getters
}
最佳答案
如果您只接收 null
或空字符串,而不是正确表示您的 PaymentType
类的 JSON 对象,则只需在ObjectMapper
:
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
现在,空字符串将被强制为 null
,您将不再遇到此问题。
更通用的方法(尽管处理起来更复杂)是向您的 PaymentType
类添加一个接受 String
参数的构造函数:
public PaymentType() {
}
public PaymentType(String json) {
// parse the json string here and initialize members
}
在接收String
参数的构造函数中,您可以根据需要解析该字符串。
请注意,您还需要添加无参数构造函数,以便 Jackson 可以从有效的 JSON 进行反序列化。
关于java - 使用 jackson wtih java 将 json 字符串转换为 pojo 时如何处理空值或 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40199045/