能够使用jackson循环从json响应返回的每个用户

时间:2018-06-22 12:51:03

标签: java json rest jackson jackson-databind

我正在使用jackson将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());
    }

1 个答案:

答案 0 :(得分:1)

尝试这样做:

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

我不确定,是否可以在此处使用泛型。