JSON-lib框架,轉換JSON、XML

Json-lib能夠將Java對象轉成json格式的字符串,也能夠將Java對象轉換成xml格式的文檔,一樣能夠將json字符串轉換成Java對象或是將xml字符串轉換成Java對象。 html

1、 準備工做  java

 

一、 首先要去官方下載json-lib工具包 git

下載地址: github

http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/ apache

目前最新的是2.4的版本,本示例中使用的是v2.3;json-lib還須要如下依賴包: json

jakarta commons-lang 2.5 數組

jakarta commons-beanutils 1.8.0 app

jakarta commons-collections 3.2.1 ide

jakarta commons-logging 1.1.1 函數

ezmorph 1.0.6

官方網址:http://json-lib.sourceforge.net/

而後在工程中添加以下jar包:

clip_image002

固然你也能夠用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

二、 要轉換的JavaBean的代碼以下:

package com.hoo.entity;
 
public class Student {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
 
//setter、getter
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
 

Birthday.java

package com.hoo.entity;
 
public class Birthday {
private String birthday;
 
  
public Birthday(String birthday) {
super();
this.birthday = birthday;
}
//setter、getter
public Birthday() {}
 
  
@Override
public String toString() {
return this.birthday;
}
}

注意,上面的getter、setter方法省略了,本身構建下。

三、 新建JsonlibTest測試類,基本代碼以下:

package com.hoo.test;
 
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONFunction;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.Birthday;
import com.hoo.entity.Student;
 
/**
 * <b>function:</b> 用json-lib轉換java對象到JSON字符串
 * 讀取json字符串到java對象,序列化jsonObject到xml
 * json-lib-version: json-lib-2.3-jdk15.jar
 * 依賴包: 
 * commons-beanutils.jar
 * commons-collections-3.2.jar
 * ezmorph-1.0.3.jar
 * commons-lang.jar
 * commons-logging.jar
 * @author hoojo
 * @createDate Nov 28, 2010 2:28:39 PM
 * @file JsonlibTest.java
 * @package com.hoo.test
 * @project WebHttpUtils
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@SuppressWarnings({ "deprecation", "unchecked" })
public class JsonlibTest {
private JSONArray jsonArray = null;
private JSONObject jsonObject = null;
 
  
private Student bean = null;
 
  
@Before
public void init() {
jsonArray = new JSONArray();
jsonObject = new JSONObject();
 
  
bean = new Student();
bean.setAddress("address");
bean.setEmail("email");
bean.setId(1);
bean.setName("haha");
Birthday day = new Birthday();
day.setBirthday("2010-11-22");
bean.setBirthday(day);
}
 
  
@After
public void destory() {
jsonArray = null;
jsonObject = null;
bean = null;
System.gc();
}
 
  
public final void fail(String string) {
System.out.println(string);
}
 
  
public final void failRed(String string) {
System.err.println(string);
}
 
  
}

上面的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的。

2、 Java對象序列化成JSON對象

一、 將JavaObject轉換吃JSON字符串

在JsonlibTest中添加以下代碼:

/*=========================Java Object >>>> JSON String ===========================*/
/**
 * <b>function:</b>轉Java Bean對象到JSON
 * @author hoojo
 * @createDate Nov 28, 2010 2:35:54 PM
 */
@Test
public void writeEntity2JSON() {
fail("==============Java Bean >>> JSON Object==================");
fail(JSONObject.fromObject(bean).toString());
fail("==============Java Bean >>> JSON Array==================");
fail(JSONArray.fromObject(bean).toString());//array會在最外層套上[]
fail("==============Java Bean >>> JSON Object ==================");
fail(JSONSerializer.toJSON(bean).toString());
 
  
fail("========================JsonConfig========================");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Birthday.class, new JsonValueProcessor() {
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
if (value == null) {
return new Date();
}
return value;
}
 
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
fail("key:" + key);
return value + "##修改過的日期";
}
 
});
jsonObject = JSONObject.fromObject(bean, jsonConfig);
 
  
fail(jsonObject.toString());
Student student = (Student) JSONObject.toBean(jsonObject, Student.class);
fail(jsonObject.getString("birthday"));
fail(student.toString());
 
  
fail("#####################JsonPropertyFilter############################");
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object source, String name, Object value) {
fail(source + "%%%" + name + "--" + value);
//忽略birthday屬性
if (value != null && Birthday.class.isAssignableFrom(value.getClass())) {
return true;
}
return false;
}
});
fail(JSONObject.fromObject(bean, jsonConfig).toString());
fail("#################JavaPropertyFilter##################");
jsonConfig.setRootClass(Student.class);
jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
public boolean apply(Object source, String name, Object value) {
fail(name + "@" + value + "#" + source);
if ("id".equals(name) || "email".equals(name)) {
value = name + "@@";
return true;
}
return false;
}
});
//jsonObject = JSONObject.fromObject(bean, jsonConfig);
//student = (Student) JSONObject.toBean(jsonObject, Student.class);
//fail(student.toString());
student = (Student) JSONObject.toBean(jsonObject, jsonConfig);
fail("Student:" + student.toString());
}

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

二、 將JavaList集合轉換吃JSON字符串

/**
 * <b>function:</b>轉換Java List集合到JSON
 * @author hoojo
 * @createDate Nov 28, 2010 2:36:15 PM
 */
@Test
public void writeList2JSON() {
fail("==============Java List >>> JSON Array==================");
List<Student> stu = new ArrayList<Student>();
stu.add(bean);
bean.setName("jack");
stu.add(bean);
fail(JSONArray.fromObject(stu).toString());
fail(JSONSerializer.toJSON(stu).toString());
}

運行此方法後,能夠看到控制檯輸出:

==============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字符串。

三、 將Map集合轉換成JSON對象

/**
 * <b>function:</b>轉Java Map對象到JSON
 * @author hoojo
 * @createDate Nov 28, 2010 2:37:35 PM
 */
@Test
public void writeMap2JSON() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("A", bean);
 
  
bean.setName("jack");
map.put("B", bean);
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){ return this.arr[i]; }");
fail("==============Java Map >>> JSON Object==================");
fail(JSONObject.fromObject(map).toString());
fail("==============Java Map >>> JSON Array ==================");
fail(JSONArray.fromObject(map).toString());
fail("==============Java Map >>> JSON Object==================");
fail(JSONSerializer.toJSON(map).toString());
}

上面的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}

四、 將更多類型轉換成JSON

/**
 * <b>function:</b> 轉換更多數組類型到JSON
 * @author hoojo
 * @createDate Nov 28, 2010 2:39:19 PM
 */
@Test
public void writeObject2JSON() {
String[] sa = {"a", "b", "c"};
fail("==============Java StringArray >>> JSON Array ==================");
fail(JSONArray.fromObject(sa).toString());
fail(JSONSerializer.toJSON(sa).toString());
fail("==============Java boolean Array >>> JSON Array ==================");
boolean[] bo = { true, false, true };
fail(JSONArray.fromObject(bo).toString());
fail(JSONSerializer.toJSON(bo).toString());
Object[] o = { 1, "a", true, 'A', sa, bo };
fail("==============Java Object Array >>> JSON Array ==================");
fail(JSONArray.fromObject(o).toString());
fail(JSONSerializer.toJSON(o).toString());
fail("==============Java String >>> JSON ==================");
fail(JSONArray.fromObject("['json','is','easy']").toString());
fail(JSONObject.fromObject("{'json':'is easy'}").toString());
fail(JSONSerializer.toJSON("['json','is','easy']").toString());
fail("==============Java JSONObject >>> JSON ==================");
jsonObject = new JSONObject()
.element("string", "JSON")
.element("integer", "1")
.element("double", "2.0")
.element("boolean", "true");
fail(JSONSerializer.toJSON(jsonObject).toString());
 
  
fail("==============Java JSONArray >>> JSON ==================");
jsonArray = new JSONArray()
.element( "JSON" )
.element( "1" )
.element( "2.0" )
.element( "true" );
fail(JSONSerializer.toJSON(jsonArray).toString());
 
  
fail("==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================");
List input = new ArrayList();
input.add("JSON");
input.add("1");
input.add("2.0");
input.add("true");
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);
System.out.println(output[0]);
 
  
fail("==============Java JSONFunction >>> JSON ==================");
String str = "{'func': function( param ){ doSomethingWithParam(param); }}";
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str);
JSONFunction func = (JSONFunction) jsonObject.get("func");
fail(func.getParams()[0]);
fail(func.getText() );
}

運行後結果以下:

==============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字符串的轉換。

3、 JSON對象反序列化成Java對象

一、 將json字符串轉成Java對象

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
/**
 * <b>function:</b>將json字符串轉化爲java對象
 * @author hoojo
 * @createDate Nov 28, 2010 3:01:16 PM
 */
@Test
public void readJSON2Bean() {
fail("==============JSON Object String >>> Java Bean ==================");
jsonObject = JSONObject.fromObject(json);
Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
fail(stu.toString());
}

運行後,結果以下:

==============JSON Object String >>> Java Bean ==================
tom#22#chian#2010-11-22#email@123.com

二、 將json字符串轉換成動態Java對象(MorphDynaBean)

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2DynaBean() {
try {
fail("==============JSON Object String >>> Java MorphDynaBean ==================");
JSON jo = JSONSerializer.toJSON(json);
Object o = JSONSerializer.toJava(jo);//MorphDynaBean
fail(PropertyUtils.getProperty(o, "address").toString());
jsonObject = JSONObject.fromObject(json);
fail(jsonObject.getString("email"));
o = JSONSerializer.toJava(jsonObject);//MorphDynaBean
fail(PropertyUtils.getProperty(o, "name").toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}

轉換後的對象Object是一個MorphDynaBean的動態JavaBean,經過PropertyUtils能夠得到指定的屬性的值。

運行後結果以下:

==============JSON Object String >>> Java MorphDynaBean =============
chian
email@123.com
tom

三、 將json字符串轉成Java的Array數組

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2Array() {
try {
fail("==============JSON Arry String >>> Java Array ==================");
json = "[" + json + "]";
jsonArray = JSONArray.fromObject(json);
fail("#%%%" + jsonArray.get(0).toString());
Object[] os = jsonArray.toArray();
System.out.println(os.length);
 
  
fail(JSONArray.fromObject(json).join(""));
fail(os[0].toString());
Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
System.out.println(stus.length);
System.out.println(stus[0]);
} catch (Exception e) {
e.printStackTrace();
}
}

運行的結果以下:

==============JSON Arry String >>> Java Array ==================
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
tom#22#chian#2010-11-22#email@123.com

四、 將JSON字符串轉成Java的List集合

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2List() {
try {
fail("==============JSON Arry String >>> Java List ==================");
json = "[" + json + "]";
jsonArray = JSONArray.fromObject(json);
List<Student> list = JSONArray.toList(jsonArray, Student.class);
System.out.println(list.size());
System.out.println(list.get(0));
 
  
list = JSONArray.toList(jsonArray);
System.out.println(list.size());
System.out.println(list.get(0));//MorphDynaBean
} catch (Exception e) {
e.printStackTrace();
}
}

運行後結果以下:

==============JSON Arry String >>> Java List ==================
1
tom#22#chian#2010-11-22#email@123.com
1
net.sf.ezmorph.bean.MorphDynaBean@141b571[
{id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[
{birthday=2010-11-22}
], address=chian, email=email@123.com, name=tom}
]

五、 將json字符串轉換成Collection接口

private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
"\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 
@Test
public void readJSON2Collection() {
try {
fail("==============JSON Arry String >>> Java Collection ==================");
json = "[" + json + "]";
jsonArray = JSONArray.fromObject(json);
Collection<Student> con = JSONArray.toCollection(jsonArray, Student.class);
System.out.println(con.size());
Object[] stt = con.toArray();
System.out.println(stt.length);
fail(stt[0].toString());
 
  
} catch (Exception e) {
e.printStackTrace();
}
}

剛纔上面的將json轉換成list提示該方法過期,這裏有toCollection,能夠用此方法代替toList方法;運行後結果以下:

==============JSON Arry String >>> Java Collection ==================
1
1
tom#22#chian#2010-11-22#email@123.com

六、 將json字符串轉換成Map集合

@Test
public void readJSON2Map() {
try {
fail("==============JSON Arry String >>> Java Map ==================");
json = "{\"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\",\"bool\":true}";
jsonObject = JSONObject.fromObject(json);
Map<String, Class<?>> clazzMap = new HashMap<String, Class<?>>();
clazzMap.put("arr", String[].class);
clazzMap.put("A", Student.class);
clazzMap.put("B", Student.class);
Map<String, ?> mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap);
System.out.println(mapBean);
 
  
Set<String> set = mapBean.keySet();
Iterator<String> iter = set.iterator();
while (iter.hasNext()) {
String key = iter.next();
fail(key + ":" + mapBean.get(key).toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}

運行後結果以下:

==============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

4、 JSON-libXML的支持

一、 將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設置節點名稱

二、 將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@15856a5
true
[Z@79ed7f
true
==============Java Object Array >>> JSON Array ==================
1
a
true
["a","b","c"]
true
["true","false","true"]
==============Java String >>> JSON ==================
json
net.sf.ezmorph.bean.MorphDynaBean@c09554[
{json=is easy}
]
is

三、 將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]; }]

就是一個數組;

相關文章
相關標籤/搜索