欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【fasterxml】json 工具类

程序员文章站 2024-02-04 09:00:46
...

直接贴代码,方便下次使用。

/**
 * json 工具类
 * <p>
 * Created by xlch at 2018/6/26
 */
public class JsonUtil {


    private JsonUtil() {

    }

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper mapper = new ObjectMapper();


    static {
        // 序列化时 是否包含 null 字段:不包含
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //反序列化时是否忽略 不存在的属性值:忽略
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 下划线转为驼峰
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);

    }


    public  static <T> T json2Object(String source, Class<T> classType) {
        try {
            return mapper.readValue(source, classType);
        } catch (IOException e) {
            LOGGER.debug("exception is ", e);
            throw new VastioException("json 读取出错");
        }
    }

    public static <T> List<T> json2ObjectList(String source, Class<T> classType) {
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, classType);
        try {
            return mapper.readValue(source, javaType);
        } catch (IOException e) {
            LOGGER.debug("exception is ", e);
            throw new VastioException("json list 读取出错");
        }
    }

    public static <T> String objects2Json(T source) {
        try {
            return mapper.writeValueAsString(source);
        } catch (JsonProcessingException e) {
            LOGGER.debug("exception is {}", e);
            throw new VastioException("json 写入出错");
        }
    }
}