日期:2014-05-18 浏览次数:20618 次
package com.armslee.json.test.cases;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
public class TestListMapJson {
/**
* @param Lavender
*/
public static void main(String[] args) {
Map<String,String> map1 = new HashMap<String,String>();
Map<String,String> map2 = new HashMap<String,String>();
Map<String,String> map3 = new HashMap<String,String>();
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
map1.put("name","小明");
map1.put("age","23");
map1.put("sex","男");
list.add(map1);
map2.put("name","小王");
map2.put("age","24");
map2.put("sex","女");
list.add(map2);
map3.put("name","小张");
map3.put("age","22");
map3.put("sex","男");
list.add(map3);
String jsonStr = JSONArray.fromObject(list).toString();
JSONArray ja = JSONArray.fromObject(jsonStr);
@SuppressWarnings({ "deprecation", "unchecked" })
List<Map<String,String>> listBack = JSONArray.toList(ja, HashMap.class);
System.out.println(listBack.size());
int i = 0;
for (Map<String, String> map : listBack) {
i++;
StringBuffer sb = new StringBuffer();
sb.append("第 "+i+" 个MAP ---》");
if(map.containsKey("name")){
sb.append(" Name:"+map.get("name"));
}
if(map.containsKey("age")){
sb.append(" Age:"+map.get("age"));
}
if(map.containsKey("sex")){
sb.append(" Sex:"+map.get("sex"));
}
System.out.println(sb.toString());
}
}
}