以下为list与jSONArray互相转换代码。
javaBean代码:
package com.test.json;
public class Student {
private int id;
private String name;
private String sex;
private int age;
private String[] hobby;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
}
转换测试代码:
package com.test.json;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
public class TestJSONObjectList {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Student student1 = new Student();
student1.setId(1);
student1.setName("jag");
student1.setSex("man");
student1.setAge(25);
student1.setHobby(new String[]{"篮球","上网","跑步","游戏"});
Student student2 = new Student();
student2.setId(1);
student2.setName("jag");
student2.setSex("man");
student2.setAge(25);
student2.setHobby(new String[]{"篮球","上网","跑步","游戏"});
List<Student> list = new ArrayList<Student>();
list.add(student1);
list.add(student2);
// List 转 JSONArray
JSONArray jsonMessage = JSONArray.fromObject(list);
//输出转换后的JSON串
System.out.println(jsonMessage.toString());
List<Student> listO = (List<Student>) JSONArray.toCollection(JSONArray.fromObject(jsonMessage) , Student.class);
Student student = null;
for(int i = 0; i < listO.size(); i++) {
student = listO.get(i);
System.out.println(student.getName());
}
}
}