1 package com.beijxing.TestMain;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 import com.beijxing.entity.Student;
 9 
10 import net.sf.json.JSONArray;
11 import net.sf.json.JSONObject;
12 
13 /**
14  * List<Object>转换为JSONArray
15  * @author ywp
16  * @version 2016年10月23日21:36:08
17  */
18 public class TestJson1 {
19     public static void main(String[] args) {
20         createJSONArray();
21     }
22     public static void createJSONArray(){
23         Student student = new Student();
24         student.setId(1);
25         student.setName("杨文培");
26         student.setSex("男");
27         //student.setAge(23);
28         student.setBirthday("1993-01-23");
29         List<String> list = new ArrayList<String>();
30         list.add("篮球");
31         list.add("乒乓球");
32         list.add("羽毛球");
33         student.setHobby(list);
34         
35         Student student2 = new Student();
36         student2.setId(1);
37         student2.setName("杨文培");
38         student2.setSex("男");
39         student.setAge(23);
40         student2.setBirthday("1993-01-23");
41         List<String> list2 = new ArrayList<String>();
42         list2.add("篮球");
43         list2.add("乒乓球");
44         list2.add("羽毛球");
45         student2.setHobby(list2);
46         
47         List<Student> list3 = new ArrayList<Student>();
48         list3.add(student);
49         list3.add(student2);
50         JSONArray jsonArray = JSONArray.fromObject(list3);
51         System.out.println("jsonArray="+jsonArray);
52         
53         JSONArray new_jsonArray = JSONArray.fromObject(jsonArray.toArray());
54         //迭代器迭代
55         Collection<JSONObject> collection = JSONArray.toCollection(new_jsonArray);
56         if(collection!=null&&!collection.isEmpty()){
57             Iterator<JSONObject> iterator = collection.iterator();
58             while(iterator.hasNext()){
59                 JSONObject jsonObject = JSONObject.fromObject(iterator.next());
60                 Student student4 = (Student) jsonObject.toBean(jsonObject,Student.class);
61                 System.out.println(student4);
62             }
63         }
64         //foreach方式迭代
65 /*        for (Object object : new_jsonArray) {
66             JSONObject jsonObject = (JSONObject) object;
67             Student student3 = (Student) jsonObject.toBean(jsonObject,Student.class);
68             System.out.println(student3);
69         }*/
70     }
71 }