(精華)將json數組和對象轉換成List和Map(小龍哥和牛徳鶴的對話)
阿新 • • 發佈:2017-07-12
put span ray add sonar string val out 和數
將java標準的數據結構ArrayList和HashMap轉換成json對象和數組很簡單
只需要JSONArray.fromObject(obj);或者JSONObject.fromObject(obj);
將json對象轉換成Map(必須用到遍歷)
public static void main(String[] args){ HashMap<String, Object> map = new HashMap<String, Object>(); map.put("name", "Tom"); map.put("age", 12); JSONObject obj =JSONObject.fromObject(map); System.out.println(obj);// {"name":"Tom","age":12} HashMap<String, Object> map1= new HashMap<String, Object>(); Iterator it =obj.keys(); while(it.hasNext()){ String key=(String)it.next(); Object value= obj.get(key); map1.put(key, value); } System.out.println(map1);//{name=Tom, age=12} System.out.println(JSONObject.fromObject(map1)); //{"name":"Tom","age":12} }
public static void main(String[] args){ ArrayList<String> list = new ArrayList<String>(); list.add("Tom"); list.add("Lisa"); System.out.println(list);//[Tom, Lisa] JSONArray array = JSONArray.fromObject(list); System.out.println(array);// ["Tom","Lisa"] ArrayList<String> list1 = new ArrayList<String>(); Iterator<String> it = list.iterator(); while(it.hasNext()){ list1.add(it.next()); } System.out.println(list1);//[Tom, Lisa] }
(精華)將json數組和對象轉換成List和Map(小龍哥和牛徳鶴的對話)