《Jackson 框架,轻易转换JSON》学习笔记

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社区相对比较活跃,更新速度也比较快。

原文地址
Jackson 框架,轻易转换JSON
http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html

以下是学习笔记:
1,改造成Maven工程后的pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.coderdream</groupId>
    <artifactId>jackson-demo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>jackson-demo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.woodstox</groupId>
            <artifactId>stax2-api</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>jackson-demo</finalName>
    </build>
</project>


2,完整的JacksonTest.java文件:
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.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
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 [email protected]
 * @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("[email protected]");
        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();
        }
    }

    /**
     * <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();
        }
    }

    /**
     * <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("[email protected]");
            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();
        }
    }

    /**
     * <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();
        }
    }

    @Test
    public void writeOthersJSON() {
        try {
            String[] arr = { "a", "b", "c" };
            System.out.println("jsonGenerator");
            String str = "hello world jackson!";
            // byte
            jsonGenerator.writeBinary(str.getBytes());
            // boolean
            jsonGenerator.writeBoolean(true);
            // null
            jsonGenerator.writeNull();
            // float
            jsonGenerator.writeNumber(2.2f);
            // char
            jsonGenerator.writeRaw("c");
            // String
            jsonGenerator.writeRaw(str, 5, 10);
            // String
            jsonGenerator.writeRawValue(str, 5, 5);
            // String
            jsonGenerator.writeString(str);
            jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
            System.out.println();

            // Object
            jsonGenerator.writeStartObject();// {
            jsonGenerator.writeObjectFieldStart("user");// user:{
            jsonGenerator.writeStringField("name", "jackson");// name:jackson
            jsonGenerator.writeBooleanField("sex", true);// sex:true
            jsonGenerator.writeNumberField("age", 22);// age:22
            jsonGenerator.writeEndObject();// }

            jsonGenerator.writeArrayFieldStart("infos");// infos:[
            jsonGenerator.writeNumber(22);// 22
            jsonGenerator.writeString("this is array");// this is array
            jsonGenerator.writeEndArray();// ]

            jsonGenerator.writeEndObject();// }

            AccountBean bean = new AccountBean();
            bean.setAddress("address");
            bean.setEmail("email");
            bean.setId(1);
            bean.setName("haha");
            // complex Object
            jsonGenerator.writeStartObject();// {
            jsonGenerator.writeObjectField("user", bean);// user:{bean}
            jsonGenerator.writeObjectField("infos", arr);// infos:[array]
            jsonGenerator.writeEndObject();// }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void readJson2Entity() {
        String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
        try {
            AccountBean acc = objectMapper.readValue(json, AccountBean.class);
            System.out.println(acc.getName());
            System.out.println(acc);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * <b>function:</b>json字符串转换成list<map>
     * 
     * @author hoojo
     * @createDate 2010-11-23 下午06:12:01
     */
    @Test
    public void readJson2List() {
        String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
                + "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
        try {
            List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class);
            System.out.println(list.size());
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                Set<String> set = map.keySet();
                for (Iterator<String> it = set.iterator(); it.hasNext();) {
                    String key = it.next();
                    System.out.println(key + ":" + map.get(key));
                }
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * <b>function:</b>json字符串转换成Array
     * 
     * @author hoojo
     * @createDate 2010-11-23 下午06:14:01
     */
    @Test
    public void readJson2Array() {
        String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
                + "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
        try {
            AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class);
            System.out.println(arr.length);
            for (int i = 0; i < arr.length; i++) {
                System.out.println(arr[i]);
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * <b>function:</b>json字符串转换Map集合
     * 
     * @author hoojo
     * @createDate Nov 27, 2010 3:00:06 PM
     */
    @Test
    public void readJson2Map() {
        String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
                + "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
        try {
            Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
            System.out.println(maps.size());
            Set<String> key = maps.keySet();
            Iterator<String> iter = key.iterator();
            while (iter.hasNext()) {
                String field = iter.next();
                System.out.println(field + ":" + maps.get(field));
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * <b>function:</b>java对象转换成xml文档 需要额外的jar包 stax2-api.jar
     * 
     * @author hoojo
     * @createDate 2010-11-23 下午06:11:21
     */
    @Test
    public void writeObject2Xml() {
        // stax2-api-3.0.2.jar
        System.out.println("XmlMapper");
        XmlMapper xml = new XmlMapper();

        try {
            // javaBean转换成xml
            // xml.writeValue(System.out, bean);
            StringWriter sw = new StringWriter();
            xml.writeValue(sw, bean);
            System.out.println(sw.toString());
            // List转换成xml
            List<AccountBean> list = new ArrayList<AccountBean>();
            list.add(bean);
            list.add(bean);
            System.out.println(xml.writeValueAsString(list));

            // Map转换xml文档
            Map<String, AccountBean> map = new HashMap<String, AccountBean>();
            map.put("A", bean);
            map.put("B", bean);
            System.out.println(xml.writeValueAsString(map));
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


3,运行结果:
jsonGenerator
{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null}
ObjectMapper
{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null}
jsonGenerator
{"account2":{"id":0,"name":null,"email":"[email protected]","address":"china-Beijin","birthday":null},"name":"hoojo","account":{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null}}
objectMapper
{"account2":{"id":0,"name":null,"email":"[email protected]","address":"china-Beijin","birthday":null},"name":"hoojo","account":{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null}}
jsonGenerator
[{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null},{"id":2,"name":"haha2","email":"email2","address":"address2","birthday":null}]
ObjectMapper
1###[{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null},{"id":2,"name":"haha2","email":"email2","address":"address2","birthday":null}]
2###[{"id":1,"name":"hoojo","email":"[email protected]","address":"china-Guangzhou","birthday":null},{"id":2,"name":"haha2","email":"email2","address":"address2","birthday":null}]
jsonGenerator
"aGVsbG8gd29ybGQgamFja3NvbiE=" true null 2.2c world jac  worl "hello world jackson!" "hello world jackson!"
 {"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]} {"user":{"id":1,"name":"haha","email":"email","address":"address","birthday":null},"infos":["a","b","c"]}
haha
haha#1#address#null#email
2
address:address2
name:haha2
id:2
email:email2
address:address
name:haha
id:1
email:email
2
haha2#2#address2#null#email2
haha#1#address#null#email
3
success:true
A:{address=address2, name=haha2, id=2, email=email2}
B:{address=address, name=haha, id=1, email=email}
XmlMapper
<AccountBean xmlns=""><id>1</id><name>hoojo</name><email>[email protected]</email><address>china-Guangzhou</address><birthday/></AccountBean>
<ArrayList xmlns=""><id>1</id><name>hoojo</name><email>[email protected]</email><address>china-Guangzhou</address><birthday/></ArrayList><zdef-485266044:ArrayList xmlns:zdef-485266044=""><zdef-485266044:id>1</zdef-485266044:id><zdef-485266044:name>hoojo</zdef-485266044:name><zdef-485266044:email>[email protected]</zdef-485266044:email><zdef-485266044:address>china-Guangzhou</zdef-485266044:address><zdef-485266044:birthday/></zdef-485266044:ArrayList>
<HashMap xmlns=""><A><id>1</id><name>hoojo</name><email>[email protected]</email><address>china-Guangzhou</address><birthday/></A><B><id>1</id><name>hoojo</name><email>[email protected]</email><address>china-Guangzhou</address><birthday/></B></HashMap>



4,git源代码地址:
https://git.oschina.net/coderdream/jackson-demo

5,源代码下载:

你可能感兴趣的:(Jackson)