常用的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> T from(String json, TypeReference typeReference) {
try {
return objectMapper.readValue(json, typeReference);
} catch (Exception e) {
throw new ServiceException();
}
}
/**
* 将json结果集转化为对象
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = objectMapper.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
throw new ServiceException();
}
}
/**
* 将json数据转换成pojo对象list
*/
public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = objectMapper.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
throw new ServiceException();
}
}
}
json反序列化用法:
public User Mock(){
return sonUtil.from(json,new TypeReference<User>() { });
}
or
public List<User> Mock(){
return sonUtil.from(json,new TypeReference<List<User>>() { });
}