---
title: "Json-JsonUtil"
author: "liumayulingyan"
date: "2014-06-25T17:45:01Z"
tags: []
categories: ["行业应用"]
slug: "json-jsonutil"
draft: false
lastmod: "2014-06-25T17:45:50Z"
id: 2085028
url: "https://liumayulingyan.iteye.com/blog/2085028"
---

http://www.open-open.com/lib/view/open1377045956584.html

 

 

Jackson解析的速度算是同类框架中最快的，同时也是Spring MVC中内置使用的解析方式。

 准备工作：

下载jar包：[http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar](http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar)  
Jackson依赖的jar包相对较少，使用起来也比较简单。  
直接贴出Jackson的相关代码，非常简单，就两个方法：

```
public class JsonUtils {
    static ObjectMapper objectMapper;

    /**
     *      使用泛型方法，把json字符串转换为相应的JavaBean对象。
     *      (1)转换为普通JavaBean：readValue(json,Student.class)
     *      (2)转换为List:readValue(json,List.class).但是如果我们想把json转换为特定类型的List，比如List<Student>，就不能直接进行转换了。
     *         因为readValue(json,List.class)返回的其实是List<Map>类型，你不能指定readValue()的第二个参数是List<Student>.class，所以不能直接转换。
     *         我们可以把readValue()的第二个参数传递为Student[].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List。
     *      (3)转换为Map：readValue(json,Map.class)
     *  我们使用泛型，得到的也是泛型
     *
     * @param content 要转换的JavaBean类型
     * @param valueType 原始json字符串数据
     * @return JavaBean对象
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            return objectMapper.readValue(content, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     *      把JavaBean转换为json字符串
     *      (1)普通对象转换：toJson(Student)
     *      (2)List转换：toJson(List)
     *      (3)Map转换:toJson(Map)
     * 我们发现不管什么类型，都可以直接传入这个方法
     *
     * @param object JavaBean对象
     * @return json字符串
     */
    public static String objToJson(Object object) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            SerializationConfig config = objectMapper.getSerializationConfig();
            config.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
            config.set(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, true);
            //config.set(SerializationConfig.Feature.INDENT_OUTPUT, true)
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
```