Json-lib可以将Java对象转成json格式的字符串,也可以将Java对象转换成xml格式的文档,同样可以将json字符串转换成Java对象或是将xml字符串转换成Java对象。
一、 准备工作
1、 首先要去官方下载json-lib工具包
下载地址:
http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/
目前最新的是2.4的版本,本示例中使用的是v2.3;json-lib还需要以下依赖包:
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
官方网址:http://json-lib.sourceforge.net/
然后在工程中添加如下jar包:
当然你也可以用2.4的json-lib库
你可以在这里看看官方提供的示例:
http://json-lib.sourceforge.net/usage.html
由于本次介绍的示例需要junit工具,所以你还需要添加junit的jar文件,版本是4.8.2版本的,下载地址:https://github.com/KentBeck/junit/downloads
如果你还不了解JSON是什么?那么你应该可以看看http://www.json.org/json-zh.html
2、 要转换的JavaBean的代码如下:
注意,上面的getter、setter方法省略了,自己构建下。
3、 新建JsonlibTest测试类,基本代码如下:
上面的init会在每个方法之前运行,destory会在每个方法完成后执行。分别用到了junit的@Before、@After注解,如果你对junit的这些注解不是很了解,可以看看junit官方的测试用例的example和doc;
JSONObject是将Java对象转换成一个json的Object形式,JSONArray是将一个Java对象转换成json的Array格式。
那什么是json的Object形式、Array形式?
用通俗易懂的方法将,所谓的json的Object形式就是一个花括号里面存放的如JavaMap的键值对,如:{name:’hoojo’, age: 24};
那么json的Array形式呢?
就是中括号,括起来的数组。如:[ ‘json’, true, 22];
如果你还想了解更多json方面的知识,请看:http://www.json.org/json-zh.html
除了上面的JSONArray、JSONObject可以将Java对象转换成JSON或是相反,将JSON字符串转换成Java对象,还有一个对象也可以完成上面的功能,它就是JSONSerializer;下面我们就来看看它们是怎么玩转Java对象和JSON的。
二、 Java对象序列化成JSON对象
1、 将JavaObject转换吃JSON字符串
在JsonlibTest中添加如下代码:
fromObject将Java对象转换成json字符串,toBean将json对象转换成Java对象;
上面方法值得注意的是使用了JsonConfig这个对象,这个对象可以在序列化的时候对JavaObject的数据进行处理、过滤等
上面的jsonConfig的registerJsonValueProcessor方法可以完成对象值的处理和修改,比如处理生日为null时,给一个特定的值。同样setJsonPropertyFilter和setJavaPropertyFilter都是完成对转换后的值的处理。
运行上面的代码可以在控制台看到如下结果:
==============Java Bean >>> JSON Object==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
==============Java Bean >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}]
==============Java Bean >>> JSON Object ==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
========================JsonConfig========================
key:birthday
{"address":"address","birthday":"2010-11-22##修改过的日期","email":"email","id":1,"name":"haha"}
2010-11-22##修改过的日期
haha#1#address#null#email
#####################JsonPropertyFilter############################
haha#1#address#2010-11-22#email%%%address--address
haha#1#address#2010-11-22#email%%%birthday--2010-11-22
haha#1#address#2010-11-22#email%%%email--email
haha#1#address#2010-11-22#email%%%id--1
haha#1#address#2010-11-22#email%%%name--haha
{"address":"address","email":"email","id":1,"name":"haha"}
#################JavaPropertyFilter##################
address@address#null#0#null#null#null
birthday@2010-11-22##修改过的日期#null#0#address#null#null
email@email#null#0#address#null#null
id@1#null#0#address#null#null
name@haha#null#0#address#null#null
Student:haha#0#address#null#null
2、 将JavaList集合转换吃JSON字符串
运行此方法后,可以看到控制台输出:
==============Java List >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
如果你是转换List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。如果你用JSONObject.fromObject方法转换List会出现异常,通常使用JSONSrializer这个JSON序列化的方法,它会自动识别你传递的对象的类型,然后转换成相应的JSON字符串。
3、 将Map集合转换成JSON对象
上面的Map集合有JavaBean、String、Boolean、Integer、以及Array和js的function函数的字符串。
运行上面的程序,结果如下:
==============Java Map >>> JSON Object==================
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}
==============Java Map >>> JSON Array ==================
[{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}]
==============Java Map >>> JSON Object==================
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}
4、 将更多类型转换成JSON
运行后结果如下:
==============Java StringArray >>> JSON Array ==================
["a","b","c"]
["a","b","c"]
==============Java boolean Array >>> JSON Array ==================
[true,false,true]
[true,false,true]
==============Java Object Array >>> JSON Array ==================
[1,"a",true,"A",["a","b","c"],[true,false,true]]
[1,"a",true,"A",["a","b","c"],[true,false,true]]
==============Java String >>> JSON ==================
["json","is","easy"]
{"json":"is easy"}
["json","is","easy"]
==============Java JSONObject >>> JSON ==================
{"string":"JSON","integer":"1","double":"2.0","boolean":"true"}
==============Java JSONArray >>> JSON ==================
["JSON","1","2.0","true"]
==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================
JSON
==============Java JSONFunction >>> JSON ==================
param
doSomethingWithParam(param);
这里还有一个JSONFunction的对象,可以转换JavaScript的function。可以获取方法参数和方法体。同时,还可以用JSONObject、JSONArray构建Java对象,完成Java对象到JSON字符串的转换。
三、 JSON对象反序列化成Java对象
1、 将json字符串转成Java对象
运行后,结果如下:
==============JSON Object String >>> Java Bean ==================
tom#22#chian#2010-11-22#[email protected]
2、 将json字符串转换成动态Java对象(MorphDynaBean)
转换后的对象Object是一个MorphDynaBean的动态JavaBean,通过PropertyUtils可以获得指定的属性的值。
运行后结果如下:
==============JSON Object String >>> Java MorphDynaBean =============3、 将json字符串转成Java的Array数组
==============JSON Arry String >>> Java Array ==================
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}
1
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}
1
tom#22#chian#2010-11-22#[email protected]
4、 将JSON字符串转成Java的List集合
运行后结果如下:
==============JSON Arry String >>> Java List ==================
1
tom#22#chian#2010-11-22#[email protected]
1
net.sf.ezmorph.bean.MorphDynaBean@141b571[
{id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[
{birthday=2010-11-22}
], address=chian, [email protected], name=tom}
]
5、 将json字符串转换成Collection接口
刚才上面的将json转换成list提示该方法过时,这里有toCollection,可以用此方法代替toList方法;运行后结果如下:
==============JSON Arry String >>> Java Collection ==================
1
1
tom#22#chian#2010-11-22#[email protected]
6、 将json字符串转换成Map集合
运行后结果如下:
==============JSON Arry String >>> Java Map ==================
{A=jack#1#address#2010-11-22#email, arr=[a, b], B=jack#1#address#2010-11-22#email, int=1, name=json, bool=true}
A:jack#1#address#2010-11-22#email
arr:[a, b]
B:jack#1#address#2010-11-22#email
int:1
name:json
bool:true
四、 JSON-lib对XML的支持
1、 将Java对象到XML
- /*============================Java Object >>>>> XML ==========================*/
- /**
- * <b>function:</b> 转换Java对象到XML
- * 需要额外的jar包:xom.jar
- * @author hoojo
- * @createDate Nov 28, 2010 2:39:55 PM
- */
- @Test
- public void writeObject2XML() {
- XMLSerializer xmlSerializer = new XMLSerializer();
- fail("==============Java String Array >>> XML ==================");
- //xmlSerializer.setElementName("bean");
- fail(xmlSerializer.write(JSONArray.fromObject(bean)));
- String[] sa = {"a", "b", "c"};
- fail("==============Java String Array >>> XML ==================");
- fail(xmlSerializer.write(JSONArray.fromObject(sa)));
- fail("==============Java boolean Array >>> XML ==================");
- boolean[] bo = { true, false, true };
- fail(xmlSerializer.write(JSONArray.fromObject(bo)));
- fail(xmlSerializer.write(JSONSerializer.toJSON(bo)));
- Object[] o = { 1, "a", true, 'A', sa, bo };
- fail("==============Java Object Array >>> JSON Array ==================");
- fail(xmlSerializer.write(JSONArray.fromObject(o)));
- fail(xmlSerializer.write(JSONSerializer.toJSON(o)));
- fail("==============Java String >>> JSON ==================");
- fail(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
- fail(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
- fail(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
- }
主要运用的是XMLSerializer的write方法,这个方法可以完成java对象到xml的转换,不过你很容易就可以看到这个xml序列化对象,需要先将java对象转成json对象,然后再将json转换吃xml文档。
运行后结果如下:
- ==============Java String Array >>> XML ==================
- <?xml version="1.0" encoding="UTF-8"?>
- <a><e class="object">
- <address type="string">address</address><birthday class="object"><birthday type="string">2010-11-22</birthday></birthday>
- <email type="string">email</email><id type="number">1</id><name type="string">haha</name>
- </e></a>
- ==============Java String Array >>> XML ==================
- <?xml version="1.0" encoding="UTF-8"?>
- <a><e type="string">a</e><e type="string">b</e><e type="string">c</e></a>
- ==============Java boolean Array >>> XML ==================
- <?xml version="1.0" encoding="UTF-8"?>
- <a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a>
- <?xml version="1.0" encoding="UTF-8"?>
- <a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a>
- ==============Java Object Array >>> JSON Array ==================
- <?xml version="1.0" encoding="UTF-8"?>
- <a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array">
- <e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e>
- <e type="boolean">false</e><e type="boolean">true</e></e></a>
- <?xml version="1.0" encoding="UTF-8"?>
- <a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array">
- <e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e>
- <e type="boolean">false</e><e type="boolean">true</e></e></a>
- ==============Java String >>> JSON ==================
- <?xml version="1.0" encoding="UTF-8"?>
- <a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a>
- <?xml version="1.0" encoding="UTF-8"?>
- <o><json type="string">is easy</json></o>
- <?xml version="1.0" encoding="UTF-8"?>
- <a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a>
上面的节点名称有点乱,你可以通过setElementName设置节点名称
2、 将XML转换成Java对象
- /*============================XML String >>>>> Java Object ==========================*/
- /**
- * <b>function:</b>转换xml文档到java对象
- * @author hoojo
- * @createDate Nov 28, 2010 3:00:27 PM
- */
- @Test
- public void readXML2Object() {
- XMLSerializer xmlSerializer = new XMLSerializer();
- fail("============== XML >>>> Java String Array ==================");
- String[] sa = {"a", "b", "c"};
- jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(sa)));
- fail(jsonArray.toString());
- String[] s = (String[]) JSONArray.toArray(jsonArray, String.class);
- fail(s[0].toString());
- fail("============== XML >>>> Java boolean Array ==================");
- boolean[] bo = { true, false, true };
- jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(bo)));
- bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
- fail(bo.toString());
- System.out.println(bo[0]);
- jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(bo)));
- bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
- fail(bo.toString());
- System.out.println(bo[0]);
- fail("==============Java Object Array >>> JSON Array ==================");
- Object[] o = { 1, "a", true, 'A', sa, bo };
- jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(o)));
- System.out.println(jsonArray.getInt(0));
- System.out.println(jsonArray.get(1));
- System.out.println(jsonArray.getBoolean(2));
- jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(o)));
- System.out.println(jsonArray.get(4));
- System.out.println(jsonArray.getJSONArray(5).get(0));
- System.out.println(jsonArray.get(5));
- fail("==============Java String >>> JSON ==================");
- jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
- s = (String[]) JSONArray.toArray(jsonArray, String.class);
- fail(s[0].toString());
- jsonObject = (JSONObject) xmlSerializer.read(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
- Object obj = JSONObject.toBean(jsonObject);
- System.out.println(obj);
- jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
- s = (String[]) JSONArray.toArray(jsonArray, String.class);
- fail(s[1].toString());
- }
主要运用到XMLSerializer的read方法,将xml内容读取后,转换成Java对象。运行后结果如下:
============== XML >>>> Java String Array ==================["a","b","c"]a============== XML >>>> Java boolean Array ==================
[Z@15856a5true[Z@79ed7ftrue==============Java Object Array >>> JSON Array ==================1atrue["a","b","c"]true["true","false","true"]==============Java String >>> JSON ==================jsonnet.sf.ezmorph.bean.MorphDynaBean@c09554[{json=is easy}]is3、 将xml的字符串内容,转换成Java的Array对象
- @Test
- public void testReadXml2Array() {
- String str = "<a class=\"array\">" +
- "<e type=\"function\" params=\"i,j\">" +
- "return matrix[i][j];" +
- "</e>" +
- "</a>";
- JSONArray json = (JSONArray) new XMLSerializer().read(str);
- fail(json.toString());
- }
上面是一段xml字符串格式的文档,将其转换为JSONArray对象。转换后结果如下:
[function(i,j){ return matrix[i][j]; }]
就是一个数组;