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的代码如下:
package com.hoo.entity;
<!--CRLF-->
<!--CRLF-->
public class Student {<!--CRLF-->
private int id;<!--CRLF-->
private String name;
<!--CRLF-->
private String email;
<!--CRLF-->
private String address;
<!--CRLF-->
private Birthday birthday;
<!--CRLF-->
<!--CRLF-->
//setter、getter
<!--CRLF-->
public String toString() {
<!--CRLF-->
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
Birthday.java
package com.hoo.entity;
<!--CRLF-->
<!--CRLF-->
public class Birthday {<!--CRLF-->
private String birthday;
<!--CRLF-->
<!--CRLF-->
public Birthday(String birthday) {
<!--CRLF-->
super();
<!--CRLF-->
this.birthday = birthday;
<!--CRLF-->
}<!--CRLF-->
//setter、getter
<!--CRLF-->
public Birthday() {}
<!--CRLF-->
<!--CRLF-->
@Override<!--CRLF-->
public String toString() {
<!--CRLF-->
return this.birthday;<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
注意,上面的getter、setter方法省略了,自己构建下。
3、 新建JsonlibTest测试类,基本代码如下:
package com.hoo.test;
<!--CRLF-->
<!--CRLF-->
import java.lang.reflect.InvocationTargetException;
<!--CRLF-->
import java.util.ArrayList;
<!--CRLF-->
import java.util.Collection;
<!--CRLF-->
import java.util.Date;
<!--CRLF-->
import java.util.HashMap;
<!--CRLF-->
import java.util.Iterator;
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import java.util.Map;
<!--CRLF-->
import java.util.Set;
<!--CRLF-->
import net.sf.json.JSON;
<!--CRLF-->
import net.sf.json.JSONArray;
<!--CRLF-->
import net.sf.json.JSONFunction;
<!--CRLF-->
import net.sf.json.JSONObject;
<!--CRLF-->
import net.sf.json.JSONSerializer;
<!--CRLF-->
import net.sf.json.JsonConfig;
<!--CRLF-->
import net.sf.json.processors.JsonValueProcessor;
<!--CRLF-->
import net.sf.json.util.PropertyFilter;
<!--CRLF-->
import net.sf.json.xml.XMLSerializer;
<!--CRLF-->
import org.apache.commons.beanutils.PropertyUtils;
<!--CRLF-->
import org.junit.After;
<!--CRLF-->
import org.junit.Before;
<!--CRLF-->
import org.junit.Test;
<!--CRLF-->
import com.hoo.entity.Birthday;
<!--CRLF-->
import com.hoo.entity.Student;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b> 用json-lib转换java对象到JSON字符串
<!--CRLF-->
* 读取json字符串到java对象,序列化jsonObject到xml
<!--CRLF-->
* json-lib-version: json-lib-2.3-jdk15.jar
<!--CRLF-->
* 依赖包:
<!--CRLF-->
* commons-beanutils.jar
<!--CRLF-->
* commons-collections-3.2.jar
<!--CRLF-->
* ezmorph-1.0.3.jar
<!--CRLF-->
* commons-lang.jar
<!--CRLF-->
* commons-logging.jar
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 28, 2010 2:28:39 PM
<!--CRLF-->
* @file JsonlibTest.java
<!--CRLF-->
* @package com.hoo.test
<!--CRLF-->
* @project WebHttpUtils
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email [email protected]
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@SuppressWarnings({ "deprecation", "unchecked" })<!--CRLF-->
public class JsonlibTest {<!--CRLF-->
private JSONArray jsonArray = null;
<!--CRLF-->
private JSONObject jsonObject = null;
<!--CRLF-->
<!--CRLF-->
private Student bean = null;
<!--CRLF-->
<!--CRLF-->
@Before<!--CRLF-->
public void init() {<!--CRLF-->
jsonArray = new JSONArray();
<!--CRLF-->
jsonObject = new JSONObject();
<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setAddress("address");
<!--CRLF-->
bean.setEmail("email");
<!--CRLF-->
bean.setId(1);<!--CRLF-->
bean.setName("haha");
<!--CRLF-->
Birthday day = new Birthday();
<!--CRLF-->
day.setBirthday("2010-11-22");
<!--CRLF-->
bean.setBirthday(day);<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
@After<!--CRLF-->
public void destory() {<!--CRLF-->
jsonArray = null;<!--CRLF-->
jsonObject = null;<!--CRLF-->
bean = null;<!--CRLF-->
System.gc();<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public final void fail(String string) {<!--CRLF-->
System.out.println(string);<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public final void failRed(String string) {<!--CRLF-->
System.err.println(string);<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
}<!--CRLF-->
上面的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中添加如下代码:
/*=========================Java Object >>>> JSON String ===========================*/
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>转Java Bean对象到JSON
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 28, 2010 2:35:54 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeEntity2JSON() {<!--CRLF-->
fail("==============Java Bean >>> JSON Object==================");
<!--CRLF-->
fail(JSONObject.fromObject(bean).toString());<!--CRLF-->
fail("==============Java Bean >>> JSON Array==================");
<!--CRLF-->
fail(JSONArray.fromObject(bean).toString());//array会在最外层套上[]
<!--CRLF-->
fail("==============Java Bean >>> JSON Object ==================");
<!--CRLF-->
fail(JSONSerializer.toJSON(bean).toString());<!--CRLF-->
<!--CRLF-->
fail("========================JsonConfig========================");
<!--CRLF-->
JsonConfig jsonConfig = new JsonConfig();
<!--CRLF-->
jsonConfig.registerJsonValueProcessor(Birthday.class, new JsonValueProcessor() {<!--CRLF-->
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
<!--CRLF-->
if (value == null) {
<!--CRLF-->
return new Date();<!--CRLF-->
}<!--CRLF-->
return value;
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
<!--CRLF-->
fail("key:" + key);
<!--CRLF-->
return value + "##修改过的日期";<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
});<!--CRLF-->
jsonObject = JSONObject.fromObject(bean, jsonConfig);<!--CRLF-->
<!--CRLF-->
fail(jsonObject.toString());<!--CRLF-->
Student student = (Student) JSONObject.toBean(jsonObject, Student.class);
<!--CRLF-->
fail(jsonObject.getString("birthday"));
<!--CRLF-->
fail(student.toString());<!--CRLF-->
<!--CRLF-->
fail("#####################JsonPropertyFilter############################");
<!--CRLF-->
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
<!--CRLF-->
public boolean apply(Object source, String name, Object value) {<!--CRLF-->
fail(source + "%%%" + name + "--" + value);<!--CRLF-->
//忽略birthday属性
<!--CRLF-->
if (value != null && Birthday.class.isAssignableFrom(value.getClass())) {<!--CRLF-->
return true;
<!--CRLF-->
}<!--CRLF-->
return false;
<!--CRLF-->
}<!--CRLF-->
});<!--CRLF-->
fail(JSONObject.fromObject(bean, jsonConfig).toString());<!--CRLF-->
fail("#################JavaPropertyFilter##################");
<!--CRLF-->
jsonConfig.setRootClass(Student.class);
<!--CRLF-->
jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
<!--CRLF-->
public boolean apply(Object source, String name, Object value) {<!--CRLF-->
fail(name + "@" + value + "#" + source);<!--CRLF-->
if ("id".equals(name) || "email".equals(name)) {<!--CRLF-->
value = name + "@@";
<!--CRLF-->
return true;
<!--CRLF-->
}<!--CRLF-->
return false;
<!--CRLF-->
}<!--CRLF-->
});<!--CRLF-->
//jsonObject = JSONObject.fromObject(bean, jsonConfig);
<!--CRLF-->
//student = (Student) JSONObject.toBean(jsonObject, Student.class);
<!--CRLF-->
//fail(student.toString());
<!--CRLF-->
student = (Student) JSONObject.toBean(jsonObject, jsonConfig);<!--CRLF-->
fail("Student:" + student.toString());
<!--CRLF-->
}<!--CRLF-->
fromObject将Java对象转换成json字符串,toBean将json对象转换成Java对象;
上面方法值得注意的是使用了JsonConfig这个对象,这个对象可以在序列化的时候对JavaObject的数据进行处理、过滤等
上面的jsonConfig的registerJsonValueProcessor方法可以完成对象值的处理和修改,比如处理生日为null时,给一个特定的值。同样setJsonPropertyFilter和setJavaPropertyFilter都是完成对转换后的值的处理。
运行上面的代码可以在控制台看到如下结果:
==============Java Bean >>> JSON Object==================<!--CRLF-->
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}<!--CRLF-->
==============Java Bean >>> JSON Array==================<!--CRLF-->
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}]<!--CRLF-->
==============Java Bean >>> JSON Object ==================<!--CRLF-->
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}<!--CRLF-->
========================JsonConfig========================<!--CRLF-->
key:birthday<!--CRLF-->
{"address":"address","birthday":"2010-11-22##修改过的日期","email":"email","id":1,"name":"haha"}<!--CRLF-->
2010-11-22##修改过的日期<!--CRLF-->
haha#1#address#null#email<!--CRLF-->
#####################JsonPropertyFilter############################<!--CRLF-->
haha#1#address#2010-11-22#email%%%address--address<!--CRLF-->
haha#1#address#2010-11-22#email%%%birthday--2010-11-22<!--CRLF-->
haha#1#address#2010-11-22#email%%%email--email<!--CRLF-->
haha#1#address#2010-11-22#email%%%id--1<!--CRLF-->
haha#1#address#2010-11-22#email%%%name--haha<!--CRLF-->
{"address":"address","email":"email","id":1,"name":"haha"}<!--CRLF-->
#################JavaPropertyFilter##################<!--CRLF-->
address@address#null#0#null#null#null<!--CRLF-->
birthday@2010-11-22##修改过的日期#null#0#address#null#null<!--CRLF-->
email@email#null#0#address#null#null<!--CRLF-->
id@1#null#0#address#null#null<!--CRLF-->
name@haha#null#0#address#null#null<!--CRLF-->
Student:haha#0#address#null#null<!--CRLF-->
2、 将JavaList集合转换吃JSON字符串
/**
<!--CRLF-->
* <b>function:</b>转换Java List集合到JSON
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 28, 2010 2:36:15 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeList2JSON() {<!--CRLF-->
fail("==============Java List >>> JSON Array==================");
<!--CRLF-->
List<Student> stu = new ArrayList<Student>();
<!--CRLF-->
stu.add(bean);<!--CRLF-->
bean.setName("jack");
<!--CRLF-->
stu.add(bean);<!--CRLF-->
fail(JSONArray.fromObject(stu).toString());<!--CRLF-->
fail(JSONSerializer.toJSON(stu).toString());<!--CRLF-->
}<!--CRLF-->
运行此方法后,可以看到控制台输出:
==============Java List >>> JSON Array==================<!--CRLF-->
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},<!--CRLF-->
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]<!--CRLF-->
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},<!--CRLF-->
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]<!--CRLF-->
如果你是转换List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。如果你用JSONObject.fromObject方法转换List会出现异常,通常使用JSONSrializer这个JSON序列化的方法,它会自动识别你传递的对象的类型,然后转换成相应的JSON字符串。
3、 将Map集合转换成JSON对象
/**
<!--CRLF-->
* <b>function:</b>转Java Map对象到JSON
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 28, 2010 2:37:35 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeMap2JSON() {<!--CRLF-->
Map<String, Object> map = new HashMap<String, Object>();
<!--CRLF-->
map.put("A", bean);
<!--CRLF-->
<!--CRLF-->
bean.setName("jack");
<!--CRLF-->
map.put("B", bean);
<!--CRLF-->
map.put("name", "json");<!--CRLF-->
map.put("bool", Boolean.TRUE);
<!--CRLF-->
map.put("int", new Integer(1));<!--CRLF-->
map.put("arr", new String[] { "a", "b" });<!--CRLF-->
map.put("func", "function(i){ return this.arr[i]; }");<!--CRLF-->
fail("==============Java Map >>> JSON Object==================");
<!--CRLF-->
fail(JSONObject.fromObject(map).toString());<!--CRLF-->
fail("==============Java Map >>> JSON Array ==================");
<!--CRLF-->
fail(JSONArray.fromObject(map).toString());<!--CRLF-->
fail("==============Java Map >>> JSON Object==================");
<!--CRLF-->
fail(JSONSerializer.toJSON(map).toString());<!--CRLF-->
}<!--CRLF-->
上面的Map集合有JavaBean、String、Boolean、Integer、以及Array和js的function函数的字符串。
运行上面的程序,结果如下:
==============Java Map >>> JSON Object==================<!--CRLF-->
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,<!--CRLF-->
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",<!--CRLF-->
"func":function(i){ return this.arr[i]; },"bool":true}<!--CRLF-->
==============Java Map >>> JSON Array ==================<!--CRLF-->
[{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,<!--CRLF-->
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",<!--CRLF-->
"func":function(i){ return this.arr[i]; },"bool":true}]<!--CRLF-->
==============Java Map >>> JSON Object==================<!--CRLF-->
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,<!--CRLF-->
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",<!--CRLF-->
"func":function(i){ return this.arr[i]; },"bool":true}<!--CRLF-->
4、 将更多类型转换成JSON
/**
<!--CRLF-->
* <b>function:</b> 转换更多数组类型到JSON
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 28, 2010 2:39:19 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeObject2JSON() {<!--CRLF-->
String[] sa = {"a", "b", "c"};<!--CRLF-->
fail("==============Java StringArray >>> JSON Array ==================");
<!--CRLF-->
fail(JSONArray.fromObject(sa).toString());<!--CRLF-->
fail(JSONSerializer.toJSON(sa).toString());<!--CRLF-->
fail("==============Java boolean Array >>> JSON Array ==================");
<!--CRLF-->
boolean[] bo = { true, false, true };
<!--CRLF-->
fail(JSONArray.fromObject(bo).toString());<!--CRLF-->
fail(JSONSerializer.toJSON(bo).toString());<!--CRLF-->
Object[] o = { 1, "a", true, 'A', sa, bo };<!--CRLF-->
fail("==============Java Object Array >>> JSON Array ==================");
<!--CRLF-->
fail(JSONArray.fromObject(o).toString());<!--CRLF-->
fail(JSONSerializer.toJSON(o).toString());<!--CRLF-->
fail("==============Java String >>> JSON ==================");
<!--CRLF-->
fail(JSONArray.fromObject("['json','is','easy']").toString());
<!--CRLF-->
fail(JSONObject.fromObject("{'json':'is easy'}").toString());
<!--CRLF-->
fail(JSONSerializer.toJSON("['json','is','easy']").toString());
<!--CRLF-->
fail("==============Java JSONObject >>> JSON ==================");
<!--CRLF-->
jsonObject = new JSONObject()
<!--CRLF-->
.element("string", "JSON")<!--CRLF-->
.element("integer", "1")<!--CRLF-->
.element("double", "2.0")<!--CRLF-->
.element("boolean", "true");<!--CRLF-->
fail(JSONSerializer.toJSON(jsonObject).toString());<!--CRLF-->
<!--CRLF-->
fail("==============Java JSONArray >>> JSON ==================");
<!--CRLF-->
jsonArray = new JSONArray()
<!--CRLF-->
.element( "JSON" )
<!--CRLF-->
.element( "1" )
<!--CRLF-->
.element( "2.0" )
<!--CRLF-->
.element( "true" );
<!--CRLF-->
fail(JSONSerializer.toJSON(jsonArray).toString());<!--CRLF-->
<!--CRLF-->
fail("==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================");
<!--CRLF-->
List input = new ArrayList();
<!--CRLF-->
input.add("JSON");
<!--CRLF-->
input.add("1");
<!--CRLF-->
input.add("2.0");
<!--CRLF-->
input.add("true");
<!--CRLF-->
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );<!--CRLF-->
JsonConfig jsonConfig = new JsonConfig();
<!--CRLF-->
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );<!--CRLF-->
Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);<!--CRLF-->
System.out.println(output[0]);<!--CRLF-->
<!--CRLF-->
fail("==============Java JSONFunction >>> JSON ==================");
<!--CRLF-->
String str = "{'func': function( param ){ doSomethingWithParam(param); }}";
<!--CRLF-->
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str);<!--CRLF-->
JSONFunction func = (JSONFunction) jsonObject.get("func");
<!--CRLF-->
fail(func.getParams()[0]);<!--CRLF-->
fail(func.getText() );<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
==============Java StringArray >>> JSON Array ==================<!--CRLF-->
["a","b","c"]<!--CRLF-->
["a","b","c"]<!--CRLF-->
==============Java boolean Array >>> JSON Array ==================
<!--CRLF-->
[true,false,true]<!--CRLF-->
[true,false,true]<!--CRLF-->
==============Java Object Array >>> JSON Array ==================<!--CRLF-->
[1,"a",true,"A",["a","b","c"],[true,false,true]]<!--CRLF-->
[1,"a",true,"A",["a","b","c"],[true,false,true]]<!--CRLF-->
==============Java String >>> JSON ==================<!--CRLF-->
["json","is","easy"]<!--CRLF-->
{"json":"is easy"}<!--CRLF-->
["json","is","easy"]<!--CRLF-->
==============Java JSONObject >>> JSON ==================<!--CRLF-->
{"string":"JSON","integer":"1","double":"2.0","boolean":"true"}<!--CRLF-->
==============Java JSONArray >>> JSON ==================<!--CRLF-->
["JSON","1","2.0","true"]<!--CRLF-->
==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================<!--CRLF-->
JSON<!--CRLF-->
==============Java JSONFunction >>> JSON ==================<!--CRLF-->
param<!--CRLF-->
doSomethingWithParam(param);<!--CRLF-->
这里还有一个JSONFunction的对象,可以转换JavaScript的function。可以获取方法参数和方法体。同时,还可以用JSONObject、JSONArray构建Java对象,完成Java对象到JSON字符串的转换。
三、 JSON对象反序列化成Java对象
1、 将json字符串转成Java对象
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +<!--CRLF-->
"\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>将json字符串转化为java对象
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 28, 2010 3:01:16 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void readJSON2Bean() {<!--CRLF-->
fail("==============JSON Object String >>> Java Bean ==================");
<!--CRLF-->
jsonObject = JSONObject.fromObject(json);<!--CRLF-->
Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
<!--CRLF-->
fail(stu.toString());<!--CRLF-->
}<!--CRLF-->
运行后,结果如下:
==============JSON Object String >>> Java Bean ==================<!--CRLF-->
tom#22#chian#2010-11-22#[email protected]<!--CRLF-->
2、 将json字符串转换成动态Java对象(MorphDynaBean)
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+<!--CRLF-->
"\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
<!--CRLF-->
<!--CRLF-->
@Test<!--CRLF-->
public void readJSON2DynaBean() {<!--CRLF-->
try {
<!--CRLF-->
fail("==============JSON Object String >>> Java MorphDynaBean ==================");
<!--CRLF-->
JSON jo = JSONSerializer.toJSON(json);<!--CRLF-->
Object o = JSONSerializer.toJava(jo);//MorphDynaBean
<!--CRLF-->
fail(PropertyUtils.getProperty(o, "address").toString());
<!--CRLF-->
jsonObject = JSONObject.fromObject(json);<!--CRLF-->
fail(jsonObject.getString("email"));
<!--CRLF-->
o = JSONSerializer.toJava(jsonObject);//MorphDynaBean
<!--CRLF-->
fail(PropertyUtils.getProperty(o, "name").toString());
<!--CRLF-->
} catch (IllegalAccessException e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
} catch (InvocationTargetException e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
} catch (NoSuchMethodException e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
转换后的对象Object是一个MorphDynaBean的动态JavaBean,通过PropertyUtils可以获得指定的属性的值。
运行后结果如下:
==============JSON Object String >>> Java MorphDynaBean =============<!--CRLF-->
chian<!--CRLF-->
[email protected]<!--CRLF-->
tom<!--CRLF-->
3、 将json字符串转成Java的Array数组
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+<!--CRLF-->
"\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
<!--CRLF-->
<!--CRLF-->
@Test<!--CRLF-->
public void readJSON2Array() {<!--CRLF-->
try {
<!--CRLF-->
fail("==============JSON Arry String >>> Java Array ==================");
<!--CRLF-->
json = "[" + json + "]";<!--CRLF-->
jsonArray = JSONArray.fromObject(json);<!--CRLF-->
fail("#%%%" + jsonArray.get(0).toString());
<!--CRLF-->
Object[] os = jsonArray.toArray();<!--CRLF-->
System.out.println(os.length);<!--CRLF-->
<!--CRLF-->
fail(JSONArray.fromObject(json).join(""));
<!--CRLF-->
fail(os[0].toString());<!--CRLF-->
Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
<!--CRLF-->
System.out.println(stus.length);<!--CRLF-->
System.out.println(stus[0]);<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
运行的结果如下:
==============JSON Arry String >>> Java Array ==================<!--CRLF-->
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}<!--CRLF-->
1<!--CRLF-->
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}<!--CRLF-->
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"[email protected]","id":22,"name":"tom"}<!--CRLF-->
1<!--CRLF-->
tom#22#chian#2010-11-22#[email protected]<!--CRLF-->
4、 将JSON字符串转成Java的List集合
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+<!--CRLF-->
"\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
<!--CRLF-->
<!--CRLF-->
@Test<!--CRLF-->
public void readJSON2List() {<!--CRLF-->
try {
<!--CRLF-->
fail("==============JSON Arry String >>> Java List ==================");
<!--CRLF-->
json = "[" + json + "]";<!--CRLF-->
jsonArray = JSONArray.fromObject(json);<!--CRLF-->
List<Student> list = JSONArray.toList(jsonArray, Student.class);
<!--CRLF-->
System.out.println(list.size());<!--CRLF-->
System.out.println(list.get(0));<!--CRLF-->
<!--CRLF-->
list = JSONArray.toList(jsonArray);<!--CRLF-->
System.out.println(list.size());<!--CRLF-->
System.out.println(list.get(0));//MorphDynaBean
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
==============JSON Arry String >>> Java List ==================<!--CRLF-->
1<!--CRLF-->
tom#22#chian#2010-11-22#[email protected]<!--CRLF-->
1<!--CRLF-->
net.sf.ezmorph.bean.MorphDynaBean@141b571[<!--CRLF-->
{id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[<!--CRLF-->
{birthday=2010-11-22}<!--CRLF-->
], address=chian, [email protected], name=tom}<!--CRLF-->
]<!--CRLF-->
5、 将json字符串转换成Collection接口
private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+<!--CRLF-->
"\"email\":\"[email protected]\",\"id\":22,\"name\":\"tom\"}";
<!--CRLF-->
<!--CRLF-->
@Test<!--CRLF-->
public void readJSON2Collection() {<!--CRLF-->
try {
<!--CRLF-->
fail("==============JSON Arry String >>> Java Collection ==================");
<!--CRLF-->
json = "[" + json + "]";<!--CRLF-->
jsonArray = JSONArray.fromObject(json);<!--CRLF-->
Collection<Student> con = JSONArray.toCollection(jsonArray, Student.class);
<!--CRLF-->
System.out.println(con.size());<!--CRLF-->
Object[] stt = con.toArray();<!--CRLF-->
System.out.println(stt.length);<!--CRLF-->
fail(stt[0].toString());<!--CRLF-->
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
刚才上面的将json转换成list提示该方法过时,这里有toCollection,可以用此方法代替toList方法;运行后结果如下:
==============JSON Arry String >>> Java Collection ==================<!--CRLF-->
1<!--CRLF-->
1<!--CRLF-->
tom#22#chian#2010-11-22#[email protected]<!--CRLF-->
6、 将json字符串转换成Map集合
@Test<!--CRLF-->
public void readJSON2Map() {<!--CRLF-->
try {
<!--CRLF-->
fail("==============JSON Arry String >>> Java Map ==================");
<!--CRLF-->
json = "{\"arr\":[\"a\",\"b\"],\"A\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
<!--CRLF-->
"\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"int\":1,"+
<!--CRLF-->
"\"B\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
<!--CRLF-->
"\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"name\":\"json\",\"bool\":true}";
<!--CRLF-->
jsonObject = JSONObject.fromObject(json);<!--CRLF-->
Map<String, Class<?>> clazzMap = new HashMap<String, Class<?>>();
<!--CRLF-->
clazzMap.put("arr", String[].class);<!--CRLF-->
clazzMap.put("A", Student.class);<!--CRLF-->
clazzMap.put("B", Student.class);<!--CRLF-->
Map<String, ?> mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap);
<!--CRLF-->
System.out.println(mapBean);<!--CRLF-->
<!--CRLF-->
Set<String> set = mapBean.keySet();<!--CRLF-->
Iterator<String> iter = set.iterator();<!--CRLF-->
while (iter.hasNext()) {
<!--CRLF-->
String key = iter.next();<!--CRLF-->
fail(key + ":" + mapBean.get(key).toString());
<!--CRLF-->
}<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
==============JSON Arry String >>> Java Map ==================<!--CRLF-->
{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}
<!--CRLF-->
A:jack#1#address#2010-11-22#email<!--CRLF-->
arr:[a, b]<!--CRLF-->
B:jack#1#address#2010-11-22#email<!--CRLF-->
int:1
<!--CRLF-->
name:json<!--CRLF-->
bool:true<!--CRLF-->
四、 JSON-lib对XML的支持
1、 将Java对象到XML
/*============================Java Object >>>>> XML ==========================*/
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b> 转换Java对象到XML
<!--CRLF-->
* 需要额外的jar包:xom.jar
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 28, 2010 2:39:55 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeObject2XML() {<!--CRLF-->
XMLSerializer xmlSerializer = new XMLSerializer();
<!--CRLF-->
fail("==============Java String Array >>> XML ==================");
<!--CRLF-->
//xmlSerializer.setElementName("bean");
<!--CRLF-->
fail(xmlSerializer.write(JSONArray.fromObject(bean)));<!--CRLF-->
String[] sa = {"a", "b", "c"};<!--CRLF-->
fail("==============Java String Array >>> XML ==================");
<!--CRLF-->
fail(xmlSerializer.write(JSONArray.fromObject(sa)));<!--CRLF-->
fail("==============Java boolean Array >>> XML ==================");
<!--CRLF-->
boolean[] bo = { true, false, true };
<!--CRLF-->
fail(xmlSerializer.write(JSONArray.fromObject(bo)));<!--CRLF-->
fail(xmlSerializer.write(JSONSerializer.toJSON(bo)));<!--CRLF-->
Object[] o = { 1, "a", true, 'A', sa, bo };<!--CRLF-->
fail("==============Java Object Array >>> JSON Array ==================");
<!--CRLF-->
fail(xmlSerializer.write(JSONArray.fromObject(o)));<!--CRLF-->
fail(xmlSerializer.write(JSONSerializer.toJSON(o)));<!--CRLF-->
fail("==============Java String >>> JSON ==================");
<!--CRLF-->
fail(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
<!--CRLF-->
fail(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
<!--CRLF-->
fail(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
<!--CRLF-->
}<!--CRLF-->
主要运用的是XMLSerializer的write方法,这个方法可以完成java对象到xml的转换,不过你很容易就可以看到这个xml序列化对象,需要先将java对象转成json对象,然后再将json转换吃xml文档。
运行后结果如下:
==============Java String Array >>> XML ==================
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<a><e class="object"><!--CRLF-->
<address type="string">address</address><birthday class="object"><birthday type="string">2010-11-22</birthday></birthday><!--CRLF-->
<email type="string">email</email><id type="number">1</id><name type="string">haha</name><!--CRLF-->
</e></a><!--CRLF-->
<!--CRLF-->
==============Java String Array >>> XML ==================
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<a><e type="string">a</e><e type="string">b</e><e type="string">c</e></a><!--CRLF-->
<!--CRLF-->
==============Java boolean Array >>> XML ==================
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a><!--CRLF-->
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a><!--CRLF-->
<!--CRLF-->
==============Java Object Array >>> JSON Array ==================
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array"><!--CRLF-->
<e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e><!--CRLF-->
<e type="boolean">false</e><e type="boolean">true</e></e></a><!--CRLF-->
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array"><!--CRLF-->
<e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e><!--CRLF-->
<e type="boolean">false</e><e type="boolean">true</e></e></a><!--CRLF-->
<!--CRLF-->
==============Java String >>> JSON ==================
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a><!--CRLF-->
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<o><json type="string">is easy</json></o><!--CRLF-->
<!--CRLF-->
<?xml version="1.0" encoding="UTF-8"?><!--CRLF-->
<a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a><!--CRLF-->
上面的节点名称有点乱,你可以通过setElementName设置节点名称
2、 将XML转换成Java对象
/*============================XML String >>>>> Java Object ==========================*/
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>转换xml文档到java对象
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 28, 2010 3:00:27 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void readXML2Object() {<!--CRLF-->
XMLSerializer xmlSerializer = new XMLSerializer();
<!--CRLF-->
fail("============== XML >>>> Java String Array ==================");
<!--CRLF-->
String[] sa = {"a", "b", "c"};<!--CRLF-->
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(sa)));<!--CRLF-->
fail(jsonArray.toString());<!--CRLF-->
<!--CRLF-->
String[] s = (String[]) JSONArray.toArray(jsonArray, String.class);
<!--CRLF-->
fail(s[0].toString());<!--CRLF-->
<!--CRLF-->
fail("============== XML >>>> Java boolean Array ==================");
<!--CRLF-->
boolean[] bo = { true, false, true };
<!--CRLF-->
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(bo)));<!--CRLF-->
bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);<!--CRLF-->
fail(bo.toString());<!--CRLF-->
System.out.println(bo[0]);<!--CRLF-->
<!--CRLF-->
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(bo)));<!--CRLF-->
bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);<!--CRLF-->
fail(bo.toString());<!--CRLF-->
System.out.println(bo[0]);<!--CRLF-->
<!--CRLF-->
fail("==============Java Object Array >>> JSON Array ==================");
<!--CRLF-->
Object[] o = { 1, "a", true, 'A', sa, bo };<!--CRLF-->
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(o)));<!--CRLF-->
System.out.println(jsonArray.getInt(0));<!--CRLF-->
System.out.println(jsonArray.get(1));<!--CRLF-->
System.out.println(jsonArray.getBoolean(2));<!--CRLF-->
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(o)));<!--CRLF-->
System.out.println(jsonArray.get(4));<!--CRLF-->
System.out.println(jsonArray.getJSONArray(5).get(0));<!--CRLF-->
System.out.println(jsonArray.get(5));<!--CRLF-->
<!--CRLF-->
fail("==============Java String >>> JSON ==================");
<!--CRLF-->
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
<!--CRLF-->
s = (String[]) JSONArray.toArray(jsonArray, String.class);
<!--CRLF-->
fail(s[0].toString());<!--CRLF-->
jsonObject = (JSONObject) xmlSerializer.read(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
<!--CRLF-->
Object obj = JSONObject.toBean(jsonObject);<!--CRLF-->
System.out.println(obj);<!--CRLF-->
jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
<!--CRLF-->
s = (String[]) JSONArray.toArray(jsonArray, String.class);
<!--CRLF-->
fail(s[1].toString());<!--CRLF-->
}<!--CRLF-->
主要运用到XMLSerializer的read方法,将xml内容读取后,转换成Java对象。运行后结果如下:
============== XML >>>> Java String Array ==================<!--CRLF-->
["a","b","c"]<!--CRLF-->
a<!--CRLF-->
============== XML >>>> Java boolean Array ==================
<!--CRLF-->
[Z@15856a5<!--CRLF-->
true<!--CRLF-->
[Z@79ed7f<!--CRLF-->
true<!--CRLF-->
==============Java Object Array >>> JSON Array ==================<!--CRLF-->
1<!--CRLF-->
a<!--CRLF-->
true<!--CRLF-->
["a","b","c"]<!--CRLF-->
true<!--CRLF-->
["true","false","true"]<!--CRLF-->
==============Java String >>> JSON ==================<!--CRLF-->
json<!--CRLF-->
net.sf.ezmorph.bean.MorphDynaBean@c09554[<!--CRLF-->
{json=is easy}<!--CRLF-->
]<!--CRLF-->
is<!--CRLF-->
3、 将xml的字符串内容,转换成Java的Array对象
@Test<!--CRLF-->
public void testReadXml2Array() {<!--CRLF-->
String str = "<a class=\"array\">" +
<!--CRLF-->
"<e type=\"function\" params=\"i,j\">" +
<!--CRLF-->
"return matrix[i][j];" +
<!--CRLF-->
"</e>" +
<!--CRLF-->
"</a>";
<!--CRLF-->
JSONArray json = (JSONArray) new XMLSerializer().read(str);
<!--CRLF-->
fail(json.toString());<!--CRLF-->
}<!--CRLF-->
上面是一段xml字符串格式的文档,将其转换为JSONArray对象。转换后结果如下:
[function(i,j){ return matrix[i][j]; }]
<!--CRLF-->
就是一个数组;