list遍历转换对象
时间: 2023-08-17 07:11:52 浏览: 197
根据引用\[1\]和引用\[2\]的内容,可以使用以下方法将List中的对象转换为Map:
```java
public Map<String, Object> objectToMap(Object obj) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(obj);
return JSON.parseObject(json, Map.class);
}
public static void convertListToMap(List<?> list) {
for (Object o : list) {
try {
Map<String, Object> map = objectToMap(o);
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
然后,你可以使用以下代码调用这个方法:
```java
Map<String, Object> map = new HashMap<>();
map.put("name1", "张三");
map.put("name2", "李四");
map.put("name3", "王五");
List<Map<String, Object>> list = new ArrayList<>();
list.add(map);
list.add(map);
list.add(map);
list.add(map);
convertListToMap(list);
```
这样就可以将List中的对象转换为Map并打印结果了。
#### 引用[.reference_title]
- *1* *2* [对象类型转换 obj转map, 集合List泛型, 接收List循环遍历](https://blog.csdn.net/sunyaqi_/article/details/129322146)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v4^insert_chatgpt"}} ] [.reference_item]
- *3* [遍历集合、集合转换](https://blog.csdn.net/weixin_42420792/article/details/115643265)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v4^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文