带你一起学习 jackson

带你一起学习 jackson

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

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

    <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 字符串的操作就叫做“写”。

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

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

// 将 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 。下面是测试代码:

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 来操作。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值