能够使用 jackson 循环从 json 响应返回的每个用户
Be able to loop every user returned from json response with jackson
我正在使用 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());
}
尝试这样做:
List<T> myUnits = objectMapper.readValue(json, objectMapper.getTypeFactory().
constructCollectionType(List.class, T.class));
我不确定,如果你可以在这里使用泛型。
我正在使用 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());
}
尝试这样做:
List<T> myUnits = objectMapper.readValue(json, objectMapper.getTypeFactory().
constructCollectionType(List.class, T.class));
我不确定,如果你可以在这里使用泛型。