import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class JsonTest { public static void main(String[] args) { String msg = "[{\"serviceCode\":\"MCY000003\",\"serviceName\":\"牀位費\",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000002\",\"serviceName\":\"牀位費\",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000001\",\"serviceName\":\"牀位費\",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000001\",\"serviceName\":\"牀位費\",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000003\",\"serviceName\":\"牀位費\",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000005\",\"serviceName\":\"牀位費\",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"}]"; groupByCode(msg); } private static Map<String, List<?>> groupByCode(String msg) { JSONArray data = JSONArray.parseArray(msg); Map<String, List<?>> dataMap = new HashMap<String, List<?>>(); //數據分組算法 for (int i = 0; i < data.size(); i++) { JSONObject json = (JSONObject)data.get(i); List<Object> tempList = (List<Object>) dataMap.get(json.get("serviceCode")); if(tempList == null) { //說明是第一次,則建立list tempList = new ArrayList<>(); tempList.add(json); dataMap.put(json.get("serviceCode").toString(), tempList);//放入map中 }else { tempList.add(json); } } //遍歷 for (String serviceCode : dataMap.keySet()) { System.out.println(serviceCode+":"+dataMap.get(serviceCode)); } return dataMap; } }