当前位置: 首页 > Web前端 > JSON > 正文

Jackson 框架,轻易转换JSON

2018-04-24 来源:cnblogs/hoojo

Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。

前面有介绍过json-lib这个框架,在线博文:http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html

相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。

一、准备工作

1、 下载依赖库jar包

Jackson的jar all下载地址:http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar

然后在工程中导入这个jar包即可开始工作

官方示例:http://wiki.fasterxml.com/JacksonInFiveMinutes

因为下面的程序是用junit测试用例运行的,所以还得添加junit的jar包。版本是junit-4.2.8

如果你需要转换xml,那么还需要stax2-api.jar

2、 测试类基本代码如下

package com.hoo.test;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.xml.XmlMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.AccountBean;
/**
 * <b>function:</b>Jackson 将java对象转换成JSON字符串,也可以将JSON字符串转换成java对象
 * jar-lib-version: jackson-all-1.6.2
 * jettison-1.0.1
 * @author hoojo
 * @createDate 2010-11-23 下午04:54:53
 * @file JacksonTest.java
 * @package com.hoo.test
 * @project Spring3
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@SuppressWarnings("unchecked")
public class JacksonTest {
    private JsonGenerator jsonGenerator = null;
    private ObjectMapper objectMapper = null;
    private AccountBean bean = null;
    @Before
    public void init() {
        bean = new AccountBean();
        bean.setAddress("china-Guangzhou");
        bean.setEmail("hoojo_@126.com");
        bean.setId(1);
        bean.setName("hoojo");
        objectMapper = new ObjectMapper();
        try {
            jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @After
    public void destory() {
        try {
            if (jsonGenerator != null) {
                jsonGenerator.flush();
            }
            if (!jsonGenerator.isClosed()) {
                jsonGenerator.close();
            }
            jsonGenerator = null;
            objectMapper = null;
            bean = null;
            System.gc();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、 所需要的JavaEntity

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

Birthday

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

二、Java对象转换成JSON

1、 JavaBean(Entity/Model)转换成JSON

/**
 * <b>function:</b>将java对象转换成json字符串
 * @author hoojo
 * @createDate 2010-11-23 下午06:01:10
 */
@Test
public void writeEntityJSON() {
    try {
        System.out.println("jsonGenerator");
        //writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
        jsonGenerator.writeObject(bean);    
        System.out.println();
        System.out.println("ObjectMapper");
        //writeValue具有和writeObject相同的功能
        objectMapper.writeValue(System.out, bean);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

运行后结果如下:

jsonGenerator
{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}
ObjectMapper
{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}

上面分别利用JsonGenerator的writeObject方法和ObjectMapper的writeValue方法完成对Java对象的转换,二者传递的参数及构造的方式不同;JsonGenerator的创建依赖于ObjectMapper对象。也就是说如果你要使用JsonGenerator来转换JSON,那么你必须创建一个ObjectMapper。但是你用ObjectMapper来转换JSON,则不需要JSONGenerator。

objectMapper的writeValue方法可以将一个Java对象转换成JSON。这个方法的参数一,需要提供一个输出流,转换后可以通过这个流来输出转换后的内容。或是提供一个File,将转换后的内容写入到File中。当然,这个参数也可以接收一个JSONGenerator,然后通过JSONGenerator来输出转换后的信息。第二个参数是将要被转换的Java对象。如果用三个参数的方法,那么是一个Config。这个config可以提供一些转换时的规则,过指定的Java对象的某些属性进行过滤或转换等。

2、 将Map集合转换成Json字符串

/**
 * <b>function:</b>将map转换成json字符串
 * @author hoojo
 * @createDate 2010-11-23 下午06:05:26
 */
@Test
public void writeMapJSON() {
    try {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", bean.getName());
        map.put("account", bean);
        bean = new AccountBean();
        bean.setAddress("china-Beijin");
        bean.setEmail("hoojo@qq.com");
        map.put("account2", bean);
        System.out.println("jsonGenerator");
        jsonGenerator.writeObject(map);
        System.out.println("");
        System.out.println("objectMapper");
        objectMapper.writeValue(System.out, map);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

转换后结果如下:

jsonGenerator
{"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"hoojo@qq.com"},"name":"hoojo",
"account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}}
objectMapper
{"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"hoojo@qq.com"},"name":"hoojo",
"account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}}

3、 将List集合转换成json

/**
 * <b>function:</b>将list集合转换成json字符串
 * @author hoojo
 * @createDate 2010-11-23 下午06:05:59
 */
@Test
public void writeListJSON() {
    try {
        List<AccountBean> list = new ArrayList<AccountBean>();
        list.add(bean);
        bean = new AccountBean();
        bean.setId(2);
        bean.setAddress("address2");
        bean.setEmail("email2");
        bean.setName("haha2");
        list.add(bean);
        System.out.println("jsonGenerator");
        //list转换成JSON字符串
        jsonGenerator.writeObject(list);
        System.out.println();
        System.out.println("ObjectMapper");
        //用objectMapper直接返回list转换成的JSON字符串
        System.out.println("1###" + objectMapper.writeValueAsString(list));
        System.out.print("2###");
        //objectMapper list转换成JSON字符串
        objectMapper.writeValue(System.out, list);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

结果如下:

jsonGenerator
[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
ObjectMapper
1###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
2###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]

外面就是多了个[]中括号;同样Array也可以转换,转换的JSON和上面的结果是一样的,这里就不再转换了。~.~