首页 > 解决方案 > 能够使用杰克逊循环从 json 响应返回的每个用户

问题描述

我使用杰克逊将我的 json 响应映射到 POJO,但是当我尝试从我的对象映射器循环返回的列表时遇到问题。

public List<T> getAll() {
    try {
        return mapper.readValue(url, new TypeReference<Collection<T>>() {});
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

错误:

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to br.com.realmpvp.commons.domain.User

示例 JSON:

    [{
        "id": {
            "timestamp": 1529630399,
            "machineIdentifier": 8647350,
            "processIdentifier": 1524,
            "counter": 321373,
            "time": 1529630399000,
            "date": 1529630399000,
            "timeSecond": 1529630399
        },
        "cash": 0,
        "currentUsername": "teste6",
        "ip": "0.0.0.0",
        "geolocation": "Portugal",
        "password": "teste",
        "usernameHistory": [
            "testeeeeeee",
            "fdsa"
        ]
    }]

我想能够做什么:

    List<User> users = info.getAll();

    for(User u : users){
        System.out.println(u.getCurrentUsername());
    }

标签: javajsonrestjacksonjackson-databind

解决方案


尝试这样做:

List<T> myUnits = objectMapper.readValue(json, objectMapper.getTypeFactory().
        constructCollectionType(List.class, T.class));

我不确定,如果你可以在这里使用泛型。


推荐阅读