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