·commons-beanutils-1.7.0
·commons-collections-3.2
·commons-lang-2.5
·commons-logging-1.1.1
·ezmorph-1.0.3
第一步:创建需要装换的Java类
public class Person{
private String name;
private int age;
private PhoneNumber homePhone;
private PhoneNumber officePhone;
super();
this.name = nema;
this.age = age;
this.homePhone=homePhone;
this.officePhone=officePhone;
}
}
public class PhoneNumber{
private String type;
private String number;
super();
this.type = type;
this.number = number;
}
}
*********************************
注意:JSON-lib不能直接读取Java类的私有属性,因此需要设置对应的set、get方法
*********************************
测试类演示了使用JSON-lib生成JSON字符串形式。
public static void main(String args[]){
PhoneNumber homePhone = new PhoneNumber("宅电","123456");
PhoneNumber officePhone = new PhoneNumber("办公电话","654321");
Person person = new Person("tom",20,homePhone,officePhone);
JSONObject json = new JSONObject.fromObject(person);
String jsonStr = json.toString();
System.out.println(jsonStr);
}
}
第三步:输出JSON格式数据
为了使生成的JSON数据格式满足ExtJs的要求,需要创建一个保存原始数据的Java类TotalJson
private long results;//记录总数
private List items;//数据列表
}
TotalJson total = new TotalJson();
total.setResults(recordTotal);
total.setItems(beanList);
JSONObject jsonArray = JSONObject.fromObject(total);
return jsonArray.toString();
}
public class JsonListTest{
public static void main(String args[]){
PhoneNumber homePhone = new PhoneNumber("宅电","123456");
PhoneNumber officePhone = new PhoneNumber("办公电话","654321");
List phoneList = new ArrayList();
phoneList.add(officePhone);
String jsonStr = ExtHelper.getJsonFromList(phoneList.size,phoneList);
System.out.println(jsonStr);
}
}