技术开发 频道

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

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

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

0
相关文章