测试类:
package edu.xjtu.lee;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
public class JSONArrayTest {
private static List<Stu> list;
private static String jsonStr;
public static void serializer(){
list = new ArrayList<Stu>();
list.add(new Stu(1, "liqiang", "fasdfas"));
list.add(new Stu(2, "zhaoyu", "dfasdfasdfas"));
list.add(new Stu(3, "jizhen", "fasdffsdafas"));
list.add(new Stu(4, "menglirong", "fasdfsdafasdfas"));
jsonStr = JSONSerializer.toJSON(list).toString();
}
public static void deSerializer(){
JSONArray ja = JSONArray.fromObject(jsonStr);
@SuppressWarnings("unchecked")
List<Stu> list = (List<Stu>)JSONArray.toCollection(ja, Stu.class);
for(int i=0; i< list.size(); i++)
System.out.println(list.get(i).getId() +" " + list.get(i).getName() +" " + list.get(i).getPhone());
}
public static void main(String[] args) {
serializer();
deSerializer();
}
}
Bean定义:
package edu.xjtu.lee;
public class Stu{
private int id;
private String name;
private String desc;
Stu(){}
Stu(int id, String name, String desc){
this.id = id;
this.name = name;
this.desc = desc;
}
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 getPhone() {
return desc;
}
public void setPhone(String desc) {
this.desc = desc;
}
}
附件为需要的jar包