package com.ots.project.tool.exam;
|
import com.alibaba.fastjson.JSONArray;
|
import com.alibaba.fastjson.JSONObject;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.databind.JavaType;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.util.List;
|
public class JsonUtil {
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
|
public static <T> String toJsonStr(T o) {
|
try {
|
return MAPPER.writeValueAsString(o);
|
} catch (JsonProcessingException e) {
|
|
}
|
return null;
|
}
|
public static <T> T toJsonObject(String json, Class<T> valueType) {
|
try {
|
return MAPPER.<T>readValue(json, valueType);
|
} catch (IOException e) {
|
|
}
|
return null;
|
}
|
public static <T> List<T> toJsonListObject(String json, Class<T> valueType) {
|
try {
|
JavaType getCollectionType = MAPPER.getTypeFactory().constructParametricType(List.class, valueType);
|
List<T> list = MAPPER.readValue(json, getCollectionType);
|
return list;
|
} catch (IOException e) {
|
logger.error("异常:{}",e.getMessage(), e);
|
}
|
return null;
|
}
|
public static <T> T toJsonObject(InputStream stream, Class<T> valueType) {
|
try {
|
T object = MAPPER.<T>readValue(stream, valueType);
|
return object;
|
} catch (IOException e) {
|
logger.error(e.getMessage(), e);
|
}
|
return null;
|
}
|
|
|
public static String toJSONString(Object object) {
|
try {
|
return JSONObject.toJSONString(object);
|
} catch (Exception e) {
|
return "";
|
}
|
}
|
|
public static <T> T parseObject(String text, Class<T> clazz) {
|
try {
|
return JSONObject.parseObject(text, clazz);
|
} catch (Exception e) {
|
return null;
|
}
|
}
|
|
public static <T> List<T> parseArray(String text, Class<T> clazz) {
|
try {
|
return JSONArray.parseArray(text, clazz);
|
} catch (Exception e) {
|
return null;
|
}
|
}
|
|
}
|