java - 能够使用杰克逊循环从 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());
}
解决方案
尝试这样做:
List<T> myUnits = objectMapper.readValue(json, objectMapper.getTypeFactory().
constructCollectionType(List.class, T.class));
我不确定,如果你可以在这里使用泛型。
推荐阅读
- facebook - 如何在 Dialogflow 意图中获取 Facebook 帐户链接事件?
- ios - 根据控制台,代表似乎无法正常工作
- javascript - React 本机元素类型无效,应为字符串
- python - 为什么元类应该从类型继承?
- spring - Spring批量远程分块
- c++ - 基于自定义 void_t 实现的成员检测
- google-maps - Google Maps V3 - 在点击功能上加载不同的标记
- javascript - switch 语句以匹配几种情况
- esp32 - 从 ESP32 上传文件到 Nextion-Display
- python - 使用 Python 脚本给出一个 Harshad 数字列表