java中json字串轉換成map/list
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map;
import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject;
public class JsonStr2MapOrList {
/** * 以"{"開頭的jsonStr轉map,map裡面有list,list裡面還裝有map */ @SuppressWarnings("rawtypes") public static Map<String, Object> jsonStr2Map(String jsonStr) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); if (!jsonStr.isEmpty()) { JSONObject json = new JSONObject(jsonStr); Iterator i = json.keys(); while (i.hasNext()) { String key = (String) i.next(); String value = json.getString(key); if (value.indexOf("{") == 0) { map.put(key.trim(), jsonStr2Map(value)); } else if (value.indexOf("[") == 0) { map.put(key.trim(), jsonStr2List(value)); } else { map.put(key.trim(), value.trim()); } } } return map; }
/** * 以"["開頭的String轉list,list裡裝有map */ public static List<Map<String, Object>> jsonStr2List(String jsonStr) throws Exception { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); JSONArray ja = new JSONArray(jsonStr); for (int j = 0; j < ja.length(); j++) { String jm = ja.getString(j); if (jm.indexOf("{") == 0) { Map<String, Object> m = jsonStr2Map(jm); list.add(m); } } return list; }
/** * jsonStr和Map之間的轉換, jsonStr和List之間的轉換 * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // 1.jsonStr和Map之間的轉換 Map<String, Object> map = new HashMap<String, Object>(); map.put("key1", "val1"); map.put("key2", "val2");
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map1 = new HashMap<String, Object>(); Map<String, Object> map2 = new HashMap<String, Object>(); map1.put("key11", "val11"); map1.put("key21", "val21"); map2.put("key111", "val111"); map2.put("key211", "val211"); list.add(map1); list.add(map2); map.put("keyList", list);
System.out.println("原始的map:" + map); String map2JsonStr = map.toString(); System.out.println("map2JsonStr:" + map2JsonStr); Map<String, Object> jsonStr2Map = jsonStr2Map(map2JsonStr); System.out.println("jsonStr2Map:" + jsonStr2Map);
// 1.jsonStr和List之間的轉換 List<Object> list_ = new ArrayList<Object>(); list_.add(map); String list_Str = list_.toString(); System.out.println("list_Str:" + list_Str); List<Map<String, Object>> listM = jsonStr2List(list_Str); System.out.println("listM:" + listM);
}
}