一、内容摘要:
1、首先要声明的是,本文仅提供了一个简单的用法,如果想对json-lib有更多了解,查看json-lib的官网:
http://json-lib.sourceforge.net/,上面有十分详细的文档,从配置到入门教程再到各种高级功能,应有尽有。
2、使用json-lib,可以将java对象转成json格式的字符串,同样也可以将json字符串转换成Java对象。下面分准备工作、主要步骤以及注意事项三部分来说明。
二、准备工作:
下载json-lib.jar:
http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/
以及所依赖的其它包(注:jakarta commons的包可以到Apache的官网下载,ezmorph可以去SourceForge下载。)
jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6
三、主要用法:
首先,要说明一下java对象与json字符串之间的简单对应关系如下:
java json-lib javascript
-----------------------------------------
Bean <=> JSONObject <=> {}
Bean[] <=> JSONArray <=> []
(注:Bean这在这里指单个Bean对象,Bean[]在这里指Bean数组/列表/集合。)
然后定义用于要用到的beanClass类及json string:
成员为primitive type的类
public class Product {
private String id;
private int barcode;
private double price;
private boolean expired;
public Product() {
}
public Product(String id, int barcode, double price, boolean expired) {
this.id = id;
this.barcode = barcode;
this.price = price;
this.expired = expired;
}
// getters and setters
...
}
成员为class type的类:(Staff类的成员department为Department类型)
public class Staff {
private String id;
private String name;
private Department department;
public Staff() {
}
public Staff(String id, String name, Department department) {
this.id = id;
this.name = name;
this.department = department;
}
// getters and setters
...
}
public class Department {
private String id;
private String name;
public Department() {
}
public Department(String id, String name) {
this.id = id;
this.name = name;
}
// getters and setters
...
}
生成对象:
Product product1 = new Product("pro001", 1111111, 100.00, false);
Product product2 = new Product("pro002", 2222222, 200.00, true);
Product[] products = {product1, product2};
Department department1 = new Department("dept001", "Martin's department");
Staff staff1 = new Staff("staff001", "Martin", department1);
Department department2 = new Department("dept001", "Flower's department");
Staff staff2 = new Staff("staff002", "Flower", department2);
Staff[] staffs = {staff1, staff2};
最后,举例说明java对象与json字符串之间如何转换。java对象与json之间的转换主要有以下四种:
(1)使用JSONObject.fromObject()方法:
//把单个Product对象转为JSONObject对象
JSONObject jsonProduct = JSONObject.fromObject(product1);
System.out.println(jsonProduct.toString());
得到:
{"barcode":1111111,"expired":false,"id":"pro001","price":100}
(2)使用JSONObject.toBean()方法:
1、当beanClass里的所有成员为原生类型(primitive type)时,即是int,boolean等类型,一般也把String当做原生类型处理。
//把前面的把JSONObject对象转回单个Product对象
Product productTest = (Product) JSONObject.toBean(jsonProduct, Product.class);
2、当beanClass里有成员为Class类型的时,即是多层Class的嵌套。
//定义一个Map类型的classMap,其key为成员的变量名,其value为成员的类型名
HashMap<String, Object> classMap = new HashMap<String, Object>();
classMap.put("department", Department.class);
//把Staff对象转为JsonObject
JSONObject jsonStaff = JSONObject.fromObject(staff1);
System.out.println(jsonStaff.toString());
得到:
{"department":{"id":"dept001","name":"Martin's department"},"id":"staff001","name":"Martin"}
//再把JsonObject转回Staff
Staff staffTest = (Staff) JSONObject.toBean(jsonStaff, Staff.class, classMap);
(3)多个Bean转为json,多个Bean对象包括列表/集合/数组,这里仅以数组为例,使用方法与(1)类似,但改为使用JSONArray.fromObject()方法:
JSONArray jsonProducts = JSONArray.fromObject(products);
System.out.println(jsonProducts.toString());
得到:
[{"barcode":1111111,"expired":false,"id":"pro001","price":100},{"barcode":2222222,"expired":true,"id":"pro002","price":200}]
(4)json转为多个Bean对象,多个Bean对象包括列表/集合/数组,这里仅以数组为例。使用方法与(2)类似,但改为使用JSONArray.toArray()方法:
1、当beanClass里的所有成员为原生类型(primitive type)时
Product[] productsTest = (Product[]) JSONArray.toArray(jsonProducts, Product.class);
2、当beanClass里有成员为Class类型的时,即是多层Class的嵌套。
JSONArray jsonStaffs = JSONArray.fromObject(staffs);
System.out.println(jsonStaffs.toString());
得到:
[{"department":{"id":"dept001","name":"Martin's department"},"id":"staff001","name":"Martin"},{"department":{"id":"dept001","name":"Flower's department"},"id":"staff002","name":"Flower"}]
//再把JsonArray转回Staff[]
Staff[] staffsTest = (Staff[]) JSONArray.toArray(jsonStaffs, Staff.class, classMap);
四、注意事项:
(1)在定义bean类时,必须确保证对于每个成员,都提供public的set/get方法。
(2)bean转为json时,返回值为JSONObject或者JSONArray类型的对象,这时可调用toString()方法得到json字符串。
(3)json转为bean时,返回值为object类型,必须进行强制转换转为beanClass,即(Product) JSONOjbect.toBean。如果是多个bean,应强制转换为beanClass数组,即(Product[]) JSONArray.toArray()。
(4)在将json转换为bean时,bean中必须有无参构造函数,否则会报找不到初始化方法的错误:
Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: Product.<init>()
at net.sf.json.JSONObject.toBean(JSONObject.java:288)
at net.sf.json.JSONObject.toBean(JSONObject.java:233)
at Tester.main(Tester.java:21)
Caused by: java.lang.NoSuchMethodException: Product.<init>()
at java.lang.Class.getConstructor0(Class.java:2813)
at java.lang.Class.getDeclaredConstructor(Class.java:2053)
at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)
at net.sf.json.JSONObject.toBean(JSONObject.java:282)
... 2 more