JacksonUtils 工具类,可直接用

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

public class JacksonUtils {

    private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(JacksonUtils.class);

    private static ObjectMapper objectMapper = new ObjectMapper();

    private static XmlMapper xmlMapper = new XmlMapper();
    static {
        // 空值不序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(sdf);
        // 忽略不存在字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true) ;
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        // 空值不序列化
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 忽略不存在字段
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * @MethodName : toJson
     * @Description : 将对象转为JSON串,此方法能够满足大部分需求
     * @param src :将要被转化的对象
     * @return :转化后的JSON串
     */
    public static String beanToJson(Object src) {
        try {
//            objectMapper.disable(SerializationFeature.WRAP_ROOT_VALUE);
            return objectMapper.writeValueAsString(src);
        } catch (JsonProcessingException jpe) {
            throw new RuntimeException("JacksonUtils beanToJson JsonProcessingException!",jpe);
        }
    }

    /**
     * @MethodName : beanToJsonWithRoot
     * @Description : 将对象转为JSON串,此方法能够满足大部分需求,且携带头部,默认为类名
     * @param src :将要被转化的对象
     * @return :转化后的JSON串
     */

    public static String beanToJsonWithRoot(Object src) {
        try {
            objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
            return objectMapper.writeValueAsString(src);
        } catch (JsonProcessingException jpe) {
            throw new RuntimeException("JacksonUtils beanToJson JsonProcessingException!",jpe);
        }
    }

    /**
     * @MethodName : jsonToBean
     * @Description : 用来将JSON串转为对象,但此方法不可用来转带泛型的集合
     * @param json
     * @param classOfT
     * @return
     */
    public static <T> T jsonToBean(String json, Class<T> classOfT) {
        try {
            objectMapper.disable(SerializationFeature.WRAP_ROOT_VALUE);
            return objectMapper.readValue(json, classOfT);
        } catch (IOException e) {
            LOGGER.error("JacksonUtils jsonToBean error! json = {},classOfT = {}", json,classOfT, e);
            throw new RuntimeException("JacksonUtils jsonToBean IO异常!");
        }
    }

    /**
     * @MethodName : jsonToBean
     * @Description : 用来将JSON串转为对象,但此方法不可用来转带泛型的集合
     * @param json
     * @param classOfT
     * @return
     */
    public static <T> T jsonToBeanWithoutRoot(String json, Class<T> classOfT) {
        try {
            objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
            T t = objectMapper.readValue(json, classOfT);
            return t;
        } catch (IOException e) {
            LOGGER.error("JacksonUtils jsonToBean error! json = {},classOfT = {}", json,classOfT, e);
            throw new RuntimeException("JacksonUtils jsonToBean IO异常!");
        } finally {
            objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
        }
    }


    /**
     * @MethodName : jsonToBean
     * @Description : 用来将JSON串转为对象,但此方法不可用来转带泛型的集合
     * @param json
     * @param typeReferenceOfT
     * @return
     */
    public static <T> T jsonToBean(String json, TypeReference<T> typeReferenceOfT) {
        try {
            return objectMapper.readValue(json, typeReferenceOfT);
        } catch (IOException e) {
            throw new RuntimeException("JacksonUtils jsonToBean IO异常!",e);
        }
    }

    /**
     * @MethodName : jsonToList
     * @Description : 用来将JSON串转为list集合
     * @param json
     * @param classOfE
     * @return
     */
    public static <E> List<E> jsonToList(String json, Class<E> classOfE) {
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, classOfE);
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            LOGGER.error("JacksonUtils jsonToBean error! json = {},classOfE = {}", json,classOfE, e);
            throw new RuntimeException("JacksonUtils jsonToList IO异常!");
        }
    }


    /**
     * @MethodName : jsonToMap
     * @Description : 用来将JSON串转为Map集合
     * @param json
     * @param classOfK
     * @param classOfV
     * @return
     */
    public static <K,V> Map<K,V> jsonToMap(String json, Class<K> classOfK, Class<V> classOfV) {
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Map.class, classOfK, classOfV);
            return objectMapper.readValue(json, javaType);
        } catch (IOException e) {
            LOGGER.error("JacksonUtils jsonToBean error! json = {},classOfK = {}, classOfV = {}", json,classOfK,classOfV, e);
            throw new RuntimeException("JacksonUtils jsonToMap IO异常!");
        }
    }



    /**
     * 校验json是否格式规范
     * @param test
     * @return
     */
    public static boolean isJsonValid(String test) {
        try {
            objectMapper.readValue(test,Object.class);
        } catch (IOException e) {
            return false;
        }
        return true;
    }


    /**
     * @MethodName : beanToXml
     * @Description : 将对象转为xml字符串
     * @param src :将要被转化的对象
     * @return :转化后的xml
     */
    public static String beanToXml(Object src) {
        try {
            return xmlMapper.writeValueAsString(src);
        } catch (JsonProcessingException jpe) {
            throw new RuntimeException("JacksonUtils beanToXml JsonProcessingException!");
        }
    }

    /**
     * @MethodName : xmlToBean
     * @Description : 用来将xml串转为对象,但此方法不可用来转带泛型的集合
     * @param xml
     * @param classOfT
     * @return
     */
    public static <T> T xmlToBean(String xml, Class<T> classOfT) {
        try {
            return xmlMapper.readValue(xml, classOfT);
        } catch (IOException e) {
            LOGGER.error("JacksonUtils xmlToBean error! xml = {},classOfT = {}", xml, classOfT, e);
            throw new RuntimeException("JacksonUtils xmlToBean IO异常!");
        }
    }

    /**
     * @MethodName : xmlToList
     * @Description : 用来将xml串转为list集合
     * @param xml
     * @param classOfE
     * @return
     */
    public static <E> List<E> xmlToList(String xml, Class<E> classOfE) {
        try {
            xmlMapper.disable(SerializationFeature.WRAP_ROOT_VALUE);
            JavaType javaType = xmlMapper.getTypeFactory().constructParametricType(List.class, classOfE);
            return xmlMapper.readValue(xml, javaType);
        } catch (IOException e) {
            LOGGER.error("JacksonUtils xmlToList error! xml = {},classOfE = {}", xml,classOfE, e);
            throw new RuntimeException("JacksonUtils xmlToList IO异常!");
        }
    }

    /**
     * @MethodName : xmlToBean
     * @Description : 用来将JSON串转为对象,但此方法不可用来转带泛型的集合
     * @param bytes
     * @param classOfT
  * @return
     */
    public static <T> T bytesToBean(byte[] bytes, Class<T> classOfT) {
        try {
            return xmlMapper.readValue(bytes,classOfT);
        } catch (IOException e) {
            throw new RuntimeException("JacksonUtils xmlToBean IO异常!");
        }
    }


    /**
     * 反序列化字符串成为对象
     * @return
     */
    public static <T> T getTFromOjbect(Object obj, Class<T> classOfT) {
        try {
            String json = objectMapper.writeValueAsString(obj);
            return objectMapper.readValue(json, classOfT);
        } catch (IOException e) {
            throw new RuntimeException("JacksonUtils getTFromOjbect IO异常!");
        }
    }

    /**
     * 反序列化字符串成为对象
     * @return
     */
    public static <T> T getTFromOjbect(Object obj, TypeReference<T> typeReferenceOfT) {
        try {
            String json = objectMapper.writeValueAsString(obj);
            return objectMapper.readValue(json, typeReferenceOfT);
        } catch (IOException e) {
            throw new RuntimeException("JacksonUtils getTFromOjbect IO异常!",e);
        }
    }

}