Java Hutool: JSONArray 转换为 List<Map<String, Object>> - 示例代码
可以使用 Hutool 中的 JSONUtil 工具类来将 JSONArray 转换为 List<Map<String, Object>>,示例代码如下:
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonArrayToListMapDemo {
public static void main(String[] args) {
String jsonStr = '[{"id":1,"name":"Tom"},{"id":2,"name":"Jerry"}]';
JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, Object> map = new HashMap<>(jsonObject.size());
for (String key : jsonObject.keySet()) {
map.put(key, jsonObject.get(key));
}
list.add(map);
}
System.out.println(list);
}
}
输出结果:
[{id=1, name=Tom}, {id=2, name=Jerry}]
在上述代码中,我们首先使用 JSONUtil.parseArray 方法将 JSONArray 解析出来,然后遍历 JSONArray,将每个 JSONObject 转换为 Map<String, Object>,并添加到 List 中。转换时,我们通过遍历 JSONObject 的 keySet,将每个键值对添加到 Map 中。最后,我们将转换后的 List 输出到控制台。
原文地址: https://www.cveoy.top/t/topic/mVuA 著作权归作者所有。请勿转载和采集!