jar引用
json数据<dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency>
完整代码[{"address": "北京","sex": "女","name": "小丽","age": "23"}, {"address": "西安","sex": "女","name": "张三","age": "20"}, {"address": "广州","sex": "男","name": "小王","age": "2"}, {"address": "广州","sex": "男","name": "王五","age": "27"}, {"address": "厦门","sex": "男","name": "小王","age": "29"}, {"address": "北京","sex": "女","name": "小丽","age": "23"}]
package com.example.exceldemo;//替换成自己java类所在的包import net.sf.json.JSONArray;import net.sf.json.JSONObject;import java.io.*;import java.util.*;/*** json数组转list<Map>*/public class JsonToList {public static void main(String[] args) {String json = readJson();JSONArray array = JSONArray.fromObject(json);List<Map<String, Object>> list = (List<Map<String, Object>>) translate(array);System.out.println(list);}/*** 读取json文件* @return*/public static String readJson(){FileInputStream inputStream = null;InputStreamReader reader = null;BufferedReader bf = null;StringBuffer sf = null;try {inputStream = new FileInputStream(new File("src/main/resources/static/json/user.json"));reader = new InputStreamReader(inputStream, "UTF-8");bf = new BufferedReader(reader);sf = new StringBuffer();String json = null;while ((json = bf.readLine()) != null) {sf.append(json);}} catch (Exception e) {e.printStackTrace();} finally {try {inputStream.close();reader.close();bf.close();} catch (IOException e) {e.printStackTrace();}}return sf.toString();}/*** 将JSONArray对象转换成List集合** @param json* @return* @see*/public static Object translate(JSONArray json) {List<Object> list = new ArrayList<Object>();for (Object o : json) {if (o instanceof JSONArray)list.add(translate((JSONArray) o));else if (o instanceof JSONObject)list.add(translate((JSONObject) o));elselist.add(o);}return list;}/*** 将JSONObjec对象转换成Map集合** @param json* @return* @see*/public static HashMap<String, Object> translate(JSONObject json) {HashMap<String, Object> map = new HashMap<String, Object>();Set keys = json.keySet();for (Object key : keys) {Object o = json.get(key);if (o instanceof JSONArray)map.put((String) key, translate((JSONArray) o));else if (o instanceof JSONObject)map.put((String) key, translate((JSONObject) o));elsemap.put((String) key, o);}return map;}}
输出
[{address=北京, sex=女, name=小丽, age=23}, {address=西安, sex=女, name=张三, age=20}, {address=广州, sex=男, name=小王, age=2}, {address=广州, sex=男, name=王五, age=27}, {address=厦门, sex=男, name=小王, age=29}, {address=北京, sex=女, name=小丽, age=23}]