当前位置: 代码迷 >> JavaScript >> JSON格式数据序列化跟反序列化
  详细解决方案

JSON格式数据序列化跟反序列化

热度:663   发布时间:2012-10-31 14:37:31.0
JSON格式数据序列化和反序列化
测试类:
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包
  相关解决方案