Jackson工具类

2022/4/7 23:49:54

本文主要是介绍Jackson工具类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package com.sasworld.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

public class JacksonUtil {
    static ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 忽略json串中多余的字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    }

    public static <T> T parseObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readerFor(clazz).readValue(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String writeAsJsonString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> jsonString2List(String jsonString, Class<T> clazz) {
        try {
            JavaType javaType = getObjectiveJavaType(List.class, clazz);
            return objectMapper.readerFor(javaType).readValue(jsonString);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对象转换为json字符串,忽略空值
     */
    public static String writeAsJsonStringIgnoreNull(Object object) {
        try {
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取集合的JavaType
     *
     * @param collectionClass
     * @param elementClasses
     * @return
     */
    public static JavaType getObjectiveJavaType(Class<?> collectionClass, 
                                                Class<?>... elementClasses) {
        return objectMapper.getTypeFactory()
                .constructParametricType(collectionClass, elementClasses);
    }
}


这篇关于Jackson工具类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程