常用的JsonUtil工具类

常用的JsonUtil工具类

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.terminus.common.exception.ServiceException;
import java.util.List;

public class JsonUtils {

    // 定义jackson对象
    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
      	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    /**
     * 将对象转换成json字符串。
     */
    public static String objectToJson(Object data) {
        try {
            String string = objectMapper.writeValueAsString(data);
            return string;
        } catch (Exception e) {
           throw new ServiceException();
        }
    }
    
    /**
    * Json反序列化
    */
	public static  T from(String json, TypeReference typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            throw new ServiceException();
        }
    }
    
    /**
     * 将json结果集转化为对象
     */
    public static  T jsonToPojo(String jsonData, Class beanType) {
        try {
            T t = objectMapper.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
           throw new ServiceException();
        }
    }

    /**
     * 将json数据转换成pojo对象list
     */
    public static  List jsonToList(String jsonData, Class beanType) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List list = objectMapper.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
           throw new ServiceException();
        }
     }
}     

json反序列化用法:

public User Mock(){
	return sonUtil.from(json,new TypeReference() { });
}

or

public List Mock(){
	return sonUtil.from(json,new TypeReference>() { });
}

你可能感兴趣的:(学习之路,json,json工具类,TypeReference)