标签:blog map span bsp iterator out new while object
将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(小龙哥和牛徳鹤的对话)
标签:blog map span bsp iterator out new while object
原文地址:http://www.cnblogs.com/cs-lcy/p/7152695.html