gpt4 book ai didi

java - 使用 Jackson 反序列化对象 json 对象列表 - 无法从 start_array token 中反序列化实例

转载 作者:行者123 更新时间:2023-12-02 09:42:55 28 4
gpt4 key购买 nike

我正在使用 Jackson 读取从 Mailchimp 的 Mandrill API 返回的 JSON 响应。对于 API 响应来说,该响应有点不传统,因为它包含方括号内的 Handlebars (对象列表)。围绕此错误的其他堆栈溢出讨论与不在列表中的 API 响应有关。

[
{
"email": "gideongrossman@gmail.com",
"status": "sent",
"_id": "6c6afbd3702f4fdea8de690c284f5898",
"reject_reason": null
}
]

我收到此错误...

2019-07-06 22:41:47.916 DESKTOP-2AB6RK0 core.RestClient 131222 ERROR com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `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 和处理响应的方式使用您的对象映射器建议?

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();
}
}

最佳答案

你可以直接将此json反序列化为List您的 Pojo 类。

给定模型类:

public class TemplatedEmailResponse {
private String email;
private String status;
private String _id;
private String reject_reason;
//getters setters
}

您可以使用 List<TemplatedEmailResponse> 的 TypeReference 反序列化此 json :

ObjectMapper mapper = new ObjectMapper();
TypeReference<List<TemplatedEmailResponse>> typeRef = new TypeReference<List<TemplatedEmailResponse>>() {};
List<TemplatedEmailResponse> list = mapper.readValue(json, typeRef);

哪里json在本例中,变量表示 json 字符串。

关于java - 使用 Jackson 反序列化对象 json 对象列表 - 无法从 start_array token 中反序列化实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919694/

28 4 0