技术开发 频道

JSON lib框架转换JSON XML不再困难!

  转换后的对象Object是一个MorphDynaBean的动态JavaBean,通过PropertyUtils可以获得指定的属性的值。

  运行后结果如下:

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

  3、 将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

  4、 将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}
]
0
相关文章