package com.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import java.util.List;
public class JsonUtil {
//定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串
* @param data Object
* @return
*/
public static String objectToJson(Object data) {
try {
String str = MAPPER.writeValueAsString(data);
return str;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成对象
* @param jsonData String
* @param beanType Class<T>
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成List集合
* @param jsonData String
* @param beanType Class<T>
* @return
*/
public static <T> List<T> jsonToList(String jsonData, Class<T> beanType){
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}