JSON格式化有问题,Jackson替换JSON格式化处理

前言描述:

在格式化对象的过程中,经常遇到我们使用阿里巴巴的JSON格式化工具包,可是后来这个包被证明有问题,有风险注入。

目前的替代方案是:

Jackson

 

工具类实现代码JSON格式化代码


import com.fasterxml.jackson.databind.*;

import java.util.ArrayList;
import java.util.List;

public class JacksonUtil {

    private static ObjectMapper mapper = new ObjectMapper()
            //设置空值不需要转换
            //.setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .enable(MapperFeature.USE_ANNOTATIONS);

    public static String toJSONString(Object object) {
        return toJSONString(object, mapper);
    }

    public static String toJSONString(Object object, ObjectMapper objectMapper) {
        String res = null;
        try {
            res = objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            res = null;
        }
        return res;
    }

    public static  T toJavaObject(String json, Class itemType) {
        return toJavaObject(json, mapper, itemType);
    }

    public static  T toJavaObject(String json, ObjectMapper objectMapper, Class itemType) {
        T t = null;
        try {
            t = objectMapper.readValue(json, itemType);
        } catch (Exception e) {
            t = null;
        }
        return t;
    }

    public static  List toJavaList(String json, Class itemType) {
        return toJavaList(json, mapper, itemType);
    }

    public static  List toJavaList(String json, ObjectMapper objectMapper, Class itemType) {
        List list = null;
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, itemType);
        try {
            list = objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}

 

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