天天看点

Jackson对字符串和对象进行转换操作工具类

直接公开代码

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class ObjectandObjetUtils<T> {

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public T objetcMapperT(Object object,Class<T> valueType) throws Exception {
        return OBJECT_MAPPER.readValue(OBJECT_MAPPER.writeValueAsString(object),valueType);
    }

    public T stringMapperT(String string,Class<T> valueType) throws Exception {
        return OBJECT_MAPPER.readValue(string,valueType);
    }

    public List<T> objetcMapperTList(Object object,Class<T> valueType) throws Exception {
        JavaType javaType =OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class,valueType);
        return OBJECT_MAPPER.readValue(OBJECT_MAPPER.writeValueAsString(object),javaType);
    }

    public List<T> stringMapperTList(String string,Class<T> valueType) throws Exception {
        JavaType javaType =OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class,valueType);
        return OBJECT_MAPPER.readValue(string,javaType);
    }
}
           

继续阅读