其他分享
首页 > 其他分享> > Jackson 工具类适用

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);
    }


}

标签:jackson,import,适用,static,simpleMapper,JsonProcessingException,Jackson,工具,ObjectM
来源: https://www.cnblogs.com/tanglianjie/p/16253564.html