jackson

jackson的一些总结

maven依赖

2.7.4
1.9.13




    org.codehaus.jackson
    jackson-core-asl
    ${jackson.asl.version}


    org.codehaus.jackson
    jackson-mapper-asl
    ${jackson.asl.version}


    com.fasterxml.jackson.core
    jackson-databind
    ${jackson.version}


    com.fasterxml.jackson.core
    jackson-core
    ${jackson.version}


    com.fasterxml.jackson.core
    jackson-annotations
    ${jackson.version}

1. 配置

Jackson 的所有类都可以认为是围绕着 ObjectMapper 对象打造的, 所以, 熟悉了 ObjectMapper 也就掌握了 Jackson

一个简单的配置如下:

static ObjectMapper objectMapper = null;
static {
objectMapper = new ObjectMapper();
// 未知字段报警,
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 不序列化空字段
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 设置时间格式
SimpleDateFormat myDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(myDateFormat);

}

大部分配置都可以通过 configure 进行配置, 

DeserializationFeature 包含了所有可以配置的枚举

2. 注解

常用注解就是 序列化和反序列化时指定名称

具体看这里

Jackson常用注解

3. 序列化-反序列化

序列化简单:

public static String toJson(Object obj) {
    try {
        return objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        logger.error("对象转换为字符串时出错", e);
    }
    return obj.toString();
}

反序列化:

1. 简单类型

public static T from( String json, Class clazz) { try { return objectMapper.readValue(json, clazz); } catch (IOException e) { logger.error("Json转换成对象时出错", e); } return null; }

2. 复杂类型

都需要使用到下面2个例子,用来返回需要实例化的对象类型

public static JavaType getComplexType(Class collectionClass, Class... elementClasses) { return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); } public static JavaType getComplexType(Class collectionClass, JavaType... elementClasses) { return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); }

举个例子(非复合泛型类型)

String str = "[1,2,3,4,5]"; // 把他序列化为 List


调用方法

public static T from(String json, Class fatherClass, Class... otherClass) { JavaType javaType = getComplexType(fatherClass, otherClass); try { return objectMapper.readValue(json, javaType); } catch (IOException e) { logger.error("Json转换成对象时出错", e); } return null; }

List list = from(str, ArrayList.class, Interger.class);

在来一个例子(复合泛型类型)

String str = "[{\"created\":\"2015-05-26\"}]"; // 把他转换为 List>

因为泛型类中嵌套了泛型类, 所以需要从内到外一个个解泛型


调用方法

public static T from(String json, Class fatherType, JavaType... otherType) { JavaType javaType = getComplexType(fatherType, otherType); try { return objectMapper.readValue(json, javaType); } catch (IOException e) { logger.error("Json转换成对象时出错", e); } return null; }

JavaType type = JsonUtils.getComplexType(HashMap.class, String.class, Object.class);
List> skus = JsonUtils.from(str, ArrayList.class, type);

即可完成复杂类型解套.

 

最后是封装的一个工具类

package crm.app.trade.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import crm.data.buyer.model.BuyerDo;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * json转换类
 * @author xionger
 */
public class JsonUtils {
    static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    static ObjectMapper objectMapper = null;
    static {
        objectMapper = new ObjectMapper();
        // 未知字段报警,
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 不序列化空字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 设置时间格式
        SimpleDateFormat myDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(myDateFormat);
    }

    public static T from( String json, Class clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            logger.error("Json转换成对象时出错", e);
        }
        return null;
    }

    public static T from(String json, Class fatherClass, Class... otherClass) {
        JavaType javaType = getComplexType(fatherClass, otherClass);
        try {
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            logger.error("Json转换成对象时出错", e);
        }
        return null;
    }

    /**
     *
     * @param collectionClass 父类型
     * @param elementClasses 子类型
     * @return
     */
    public static JavaType getComplexType(Class collectionClass, Class... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    public static JavaType getComplexType(Class collectionClass, JavaType... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    public static List fromArray( String json, Class clazz) {
        JavaType javaType = getComplexType(ArrayList.class, clazz);
        try {
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            logger.error("Json转换成对象时出错", e);
        }
        return null;
    }

    public static Map fromMap(String json, Class keyClass, Class valueClass) {
        JavaType javaType = getComplexType(HashMap.class, keyClass, valueClass);
        try {
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            logger.error("Json转换成对象时出错", e);
        }
        return null;
    }

    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("对象转换为字符串时出错", e);
        }
        return obj.toString();
    }

    public static T convertMapToBean(Map trade, Class clazz) {
        return from(toJson(trade), clazz);
    }

    public static Map beanToMap(T obj) {
        Map params = new HashMap(0);
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!"class".equals(name)) {
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
                }
            }
        } catch (Exception e) {
            logger.error("实体类转Map失败" + e);
        }
        return params;
    }

    public static T from(String json, Class fatherType, JavaType... otherType) {
        JavaType javaType = getComplexType(fatherType, otherType);
        try {
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            logger.error("Json转换成对象时出错", e);
        }
        return null;
    }
}

你可能感兴趣的:(开发工具)