【问题标题】:deserializing a list of objects json object with jackson - cannot deserialize instance out of start_array token使用杰克逊反序列化对象列表 json 对象 - 无法从 start_array 令牌中反序列化实例
【发布时间】:2019-11-17 01:40:47
【问题描述】:

我正在使用杰克逊从 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 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...我如何准确地使用您的 objectmapper 建议与我当前调用 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();
    }
}

【问题讨论】:

    标签: java json jackson mapping


    【解决方案1】:

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

    给定模型类:

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

    您可以使用 List&lt;TemplatedEmailResponse&gt; 的 TypeReference 反序列化此 json:

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

    这里json变量代表json字符串。

    【讨论】:

    • 干杯!我编辑了我的问题,要求澄清你的答案。
    猜你喜欢
    • 2016-04-10
    • 1970-01-01
    • 2017-10-10
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多