个人技术分享

在网上找了一大堆 没找到合适的

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class JsonUtil {
    public static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        //反序列化时,忽略目标对象没有的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    }

    public static String toJsonString(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (Exception e) {
            log.error("JsonProcessingException:", e);
        }
        return "";
    }

    public static <T> T toObject(String s, Class<T> var) {
        try {
            return objectMapper.readValue(s, var);
        } catch (IOException e) {
            log.error("IOException:", e);
        }
        return null;
    }


    public static <T> List<T> toList(String s, Class<T> var) {
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, var);
            return objectMapper.readValue(s, javaType);
        } catch (IOException e) {
            log.error("IOException:", e);
        }
        return null;
    }

}