---
title: "JSON-lib框架，转换JSON、XML不再困难"
author: "ictch"
date: "2011-06-21T15:09:08Z"
tags: []
categories: ["移动开发"]
slug: "json-lib-json-xml"
draft: false
lastmod: "2011-06-21T15:09:08Z"
id: 1099701
url: "https://ictch.iteye.com/blog/1099701"
---

**一、 准备工作** 

 1、 首先要去官方下载json-lib工具包

下载地址：

[http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/](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/](http://json-lib.sourceforge.net/)

然后在工程中添加如下jar包：

![\](http://edu.codepub.com/uploadfile/2011/0429/20110429034258633.jpg)

当然你也可以用2.4的json-lib库

你可以在这里看看官方提供的示例：

[http://json-lib.sourceforge.net/usage.html](http://json-lib.sourceforge.net/usage.html)

由于本次介绍的示例需要junit工具，所以你还需要添加junit的jar文件，版本是4.8.2版本的，下载地址：[https://github.com/KentBeck/junit/downloads](https://github.com/KentBeck/junit/downloads)

如果你还不了解JSON是什么？那么你应该可以看看[http://www.json.org/json-zh.html](http://www.json.org/json-zh.html)

2、 要转换的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方法省略了，自己构建下。

3、 新建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](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 ===========================*/
```

```
/**
```

```
 * <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
```

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

3、 将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]; }"); 
```

```
 
```