您的位置:首页 > 其它

带你一起学习 jackson

2015-06-17 14:43 274 查看
带你一起学习 jackson

jackson 是我在项目里学习到的一个将 Java 对象和 json 字符串进行转换的工具。

下面记录一下我的实践。

为了避免引入包的复杂,我新建了一个 Maven 项目。pom 文件的配置片段如下。

[code]    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jackson.version>2.5.4</jackson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>


我们先介绍一下最最常用的类 ObjectMapper ,使用这个类我们可以完成在项目中绝大部分的操作。

1、从 Java 对象转换成 json 字符串(写 Value 出去)

jackson 使用了 io 流的方式命令了这个方法,将这种操作定义为写,因为这里我们将 java 对象定义为计算机内存中的对象,我们的输出可以是各种输出流,所以将 java 对象转换为 json 字符串的操作就叫做“写”。

[code]String json_str = objectMapper.writeValueAsString(account);
            System.out.println("将 Account 转换为字符串:" + json_str);


2、从 json 字符串转换为 Java 对象(读 Value 进来)

[code]// 将 json 格式的字符串转换成 Java 对象
            Account account_from_json = objectMapper
                    .readValue(
                            "{\"id\":1,\"name\":\"李威\",\"address\":\"上海市长宁区\",\"birthday\":{\"birthday\":\"1987年7月6日\"}}",
                            Account.class);
            System.out.println(account_from_json);


这就是一个简简单单的 hello world 。下面是测试代码:

[code]public class Test01 {
    private ObjectMapper objectMapper = null;

    @Before
    public void setUp() {
        objectMapper = new ObjectMapper();
    }

    @Test
    public void test01() {
        // 将 Java 对象转换成字符串
        Account account = new Account();
        account.setId(1);
        account.setAddress("上海市长宁区");
        account.setName("李威");
        Birthday birthday = new Birthday();
        birthday.setBirthday("1987年7月6日");
        account.setBirthday(birthday);

        try {
            String json_str = objectMapper.writeValueAsString(account);
            System.out.println("将 Account 转换为字符串:" + json_str);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test02() {

        try {
            // 将 json 格式的字符串转换成 Java 对象
            Account account_from_json = objectMapper
                    .readValue(
                            "{\"id\":1,\"name\":\"李威\",\"address\":\"上海市长宁区\",\"birthday\":{\"birthday\":\"1987年7月6日\"}}",
                            Account.class);
            System.out.println(account_from_json);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}


这里还提供了一种将对象转换为 String 的方式。与上面的方法不同的是,我们使用了 JsonGenerator 来操作。

[code]public static void main(String[] args) {
        JsonGenerator jsonGererator = null;
        ObjectMapper objectMapper = new ObjectMapper();
        Account account = new Account();
        account.setId(1);
        account.setAddress("上海市长宁区");
        account.setName("李威");
        Birthday birthday = new Birthday();
        birthday.setBirthday("1987年7月6日");
        account.setBirthday(birthday);

        try {
            jsonGererator = objectMapper.getJsonFactory().createGenerator(System.out, JsonEncoding.UTF8);
            jsonGererator.writeObject(account);
            System.out.println("");
            // objectMapper.writeValue(System.out, account);
            System.out.println("");
            account.setName("袁练");
            String json_str = objectMapper.writeValueAsString(account);
            // jackson 只能输出一次
            System.out.println("ObjectMapper 输出的字符串:" + json_str);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


以上的内容参考了下面的文章:

Jackson 框架,轻易转换JSON

http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html

下面是我的这一份示例代码在 github 的 url ,欢迎大家现在查看或者 clone。

https://github.com/weimingge14/JacksonDemo

下面是一份详细介绍 jackson 的系列博文,我也正在学习中:

http://blog.csdn.net/songyongfeng/article/details/6932655
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: