Jackson 工具类适用

jackson工具类使用

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

public class JsonUtil {

    private static ObjectMapper simpleMapper = new ObjectMapper();

    private static ObjectMapper fullMapper = new ObjectMapper();

    static {
        simpleMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        simpleMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT);

        fullMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        fullMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.EVERYTHING);

    }

    public static String toJsonString(Object obj) throws JsonProcessingException {
        return simpleMapper.writeValueAsString(obj);
    }

    public static String toJsonStringWithProperty(Object obj) throws JsonProcessingException {
        return fullMapper.writeValueAsString(obj);
    }

    public static <T> T fromJsonString(String jsonStr, Class<T> type) throws JsonProcessingException {
        return simpleMapper.readValue(jsonStr, type);
    }

    public static <T> T fromJsonStringWithProperty(String jsonStr, Class<T> type) throws JsonProcessingException {
        return fullMapper.readValue(jsonStr, type);
    }


}
posted @ 2022-05-10 14:48  原来是晴天啊  阅读(186)  评论(0编辑  收藏  举报