需要的包:
1.commons-lang.jar
2.commons-beanutils.jar
3.commons-collections.jar
4.commons-logging.jar
5.ezmorph.jar
6.json-lib-2.2.2-jdk15.jar
测试的例子:
可以用这个方法JSONArray.fromObject(list).toString();
1 import java.util.ArrayList; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.ListIterator; 5 import java.util.Map; 6 7 import net.sf.json.JSONArray; 8 9 import com.yan.entity.Student; 10 11 public class List2Json { 12 13 public static void main(String[] args) { 14 List<Object> list = new ArrayList<Object>(); 15 List<Map<String, Object>> sublist = new ArrayList<Map<String, Object>>(); 16 Map<String, Object> map = new HashMap<String, Object>(); 17 18 map.put("abc", "123456"); 19 map.put("def", "hmm"); 20 map.put("defddf", "ftffff"); 21 list.add(map); 22 23 Map<String, Object> map1 = new HashMap<String, Object>(); 24 map1.put("fff", "hhhh"); 25 map1.put("ggg", "jjj"); 26 map1.put("kk", "dffff"); 27 sublist.add(map1); 28 29 Student st = new Student(); 30 st.setSid(1); 31 st.setName("alec"); 32 st.setTeacher("scott"); 33 34 list.add(st); 35 36 list.add(sublist); 37 JSONArray json = new JSONArray(); 38 json.addAll(list); 39 json.listIterator(); 40 if(json.isEmpty()){ 41 System.out.println("dfdfdf"); 42 } 43 ListIterator li = json.listIterator(); 44 while(li.hasNext()){ 45 System.out.println(li.next().toString()); 46 } 47 } 48 49 }
上面用到的一个简单的entity
1 public class Student { 2 3 public Integer sid; 4 public String name; 5 public String teacher; 6 7 public Integer getSid() { 8 return sid; 9 } 10 public void setSid(Integer sid) { 11 this.sid = sid; 12 } 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public String getTeacher() { 20 return teacher; 21 } 22 public void setTeacher(String teacher) { 23 this.teacher = teacher; 24 } 25 }