我正在读取来自带有杰克逊的Mailchimp的Mandrill API的JSON响应。该响应对于API响应而言有点不常规,因为它包括方括号内的把手-对象列表。关于此错误的其他堆栈溢出讨论与不在列表中的API响应有关。
[
{
"email": "gideongrossman@gmail.com",
"status": "sent",
"_id": "6c6afbd3702f4fdea8de690c284f5898",
"reject_reason": null
}
]
我收到此错误...
2019-07-06 22:41:47.916 DESKTOP-2AB6RK0 org.groundlist.core.RestClient 131222 ERROR com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.groundlist.core.user.MandrillWrapper$TemplatedEmailResponse` out of START_ARRAY token
定义此响应对象的正确方法是什么?
我尝试用以下类型定义响应。没有工作。
public static class TemplatedEmailResponse {
public LinkedHashMap<String, String>[] response;
}
public static class TemplatedEmailResponse {
public ArrayList<LinkedHashMap<String, String>> response;
}
@milchalk ...我当前如何调用API和处理响应时,如何正确使用您的objectmapper建议?
TemplatedEmailResponseList ret = getClient("messages/send-template.json").post(mandrillPayload,
TemplatedEmailResponseList.class);
其中
public <T> T post(Object payload, Class<T> responseType) {
try {
Entity<Object> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
T t = client.target(url).request(MediaType.APPLICATION_JSON).post(entity, responseType);
return t;
} catch (Throwable t) {
logError(t);
throw t;
} finally {
client.close();
}
}
答案 0 :(得分:1)
您可以将此json直接反序列化到您的Pojo类的List
。
给出模型类:
public class TemplatedEmailResponse {
private String email;
private String status;
private String _id;
private String reject_reason;
//getters setters
}
您可以使用TypeReference为List<TemplatedEmailResponse>
反序列化此json:
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<TemplatedEmailResponse>> typeRef = new TypeReference<List<TemplatedEmailResponse>>() {};
List<TemplatedEmailResponse> list = mapper.readValue(json, typeRef);
在这种情况下,json
变量代表json字符串。