`

java中使用json-lib.jar实现bean与json的之间转换(primitive类型以及嵌套class)

 
阅读更多
一、内容摘要:
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
分享到:
评论

相关推荐

    apt-mirror-api-0.1.jar

    Files contained in apt-mirror-api-0.1.jar: META-INF/MANIFEST.MF META-INF/maven/com.moparisthebest.aptIn16/apt-mirror-api/pom.properties META-INF/maven/...

    ezmorph-1.0.6.jar

    使用json时候将会用到的一个jar包,发现这个包在网上提供的比较少....EZMorph支持原始数据类型(Primitive),对象(Object),多维护数组转换与DynaBeans的转换。兼容JDK1.3.1,整个类库大小只有76K左右。

    java jdk18 签名算法jar bcprov-jdk18on-1.72.jar

    org.springframework.web.util.NestedServletException: Handler ... nested exception is java.lang.NoSuchMethodError: org.bouncycastle.asn1.ASN1InputStream.readObject()Lorg/bouncycastle/asn1/ASN1Primitive;

    ezmorph.jar v1.0.6免费版.zip

    ezmorph.jar包是在使用json时候将会用到jar包,缺少这个包可能导致Could not initialize class net.sf.json.JsonConfig,给大家提供ezmorph-1.0.6.jar,有需要的赶快下载吧! ezmorph.jar基本简介 EZMorph是一个...

    ezmorph-1.0.6.jar包

    EZMorph是一个简单的java类库用于将一种...EZMorph原先是Json-lib项目中的转换器。EZMorph支持原始数据类型(Primitive),对象(Object),多维数组转换与DynaBeans的转换。兼容JDK1.3.1,整个类库大小只有76K左右。

    axis2-1.4.1.jar.zip

    不要在定义 wsdl 时使用 byte, int, long 等 primitive 数据类型的数组,而应该使用 base64Binary 类型。 因为从上面的例子不难看出对一上字节进行表达的 soap 消息使用了过多的冗余信息,极有可能导致效率问题。 ...

    ezmorph-1.0.6.zip

    ezmorph-1.0.6.jar ezmorph是一个简单的java类库用于将一种对象转换成另外一种对象...ezmorph原先是Json-lib项目中的转换器。EZMorph支持原始数据类型(Primitive),对象(Object),多维数组转换与DynaBeans的转换。

    PyPI 官网下载 | stmbplus_thinclient_primitive-1.0.tar.gz

    资源来自pypi官网。 资源全名:stmbplus_thinclient_primitive-1.0.tar.gz

    Hive - A Warehousing Solution Over a Map-Reduce.pdf

    tem with support for tables containing primitive types, col- lections like arrays and maps, and nested compositions of the same. The underlying IO libraries can be extended to query data in custom ...

    ezmorph-1.0.6源码及jar包

    简单的java类库用于将一种对象转换成另外一种对象。支持原始数据类型(Primitive),对象(Object),多维数组转换与DynaBeans的转换。兼容JDK1.3.1,整个类库大小只有76K左右。

    rh-nodejs8-nodejs-is-primitive-2.0.0-5.el7.noarch.rpm

    官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装

    rh-nodejs6-nodejs-is-primitive-2.0.0-5.el7.noarch.rpm

    官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装

    rh-nodejs6-nodejs-is-primitive-2.0.0-4.el7.noarch.rpm

    官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装

    jna-4.2.2 官方原版下载

    Automatic mapping from Java to native functions, with simple mappings for all primitive data types Runs on most platforms which support Java Automatic conversion between C and Java strings, with ...

    ch02-primitive-data-definite-loops.pdf

    java 基础入门学习1-18章节,连续上传。希望对大家有帮助

    Sammie Bae - JavaScript Data Structures and Algorithms - 2019.pdf

    and then lays out the basic JavaScript foundations, such as primitive objects and types. Then, this book covers implementations and algorithms for fundamental data structures such as linked lists, ...

    DRAW-PRIMITIVE.zip_draw primitive_things

    It draws things like triangles, stars etc... on console

    Thinking in Java 4th Edition

    Special case: primitive types ....... 43 Arrays in Java .............................. 44 You never need to destroy an object .................. 45 Scoping ........................................ 45 ...

    Cesium-1.80.zip

    1.添加了在半透明的3D Tiles绘制地面Primitive对象的支持; 2. 修复了地形夸张问题; 3.修复了对表面距离为0.0的某些小菱形进行插值不会返回预期结果的问题; 4.Cesium3DTileset.url已删除,使用Cesium3DTileset....

    Thinking in JAVA 4th英文版

    以下目录 是直接从pdf 中复制的: What’s Inside Preface 1 Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4 edition........................ 2 th Changes ....

Global site tag (gtag.js) - Google Analytics