import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import reactor.util.annotation.NonNull;
public class JsonUtils {
private static ObjectMapper mapper = new ObjectMapper();
/**
* 序列化,将对象转化为json字符串
*
* @param data
* @return
*/
public static String toJsonString(Object data) {
if (data == null) {
return null;
}
String json = null;
try {
json = mapper.writeValueAsString(data);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
return json;
}
/**
* 反序列化,将json字符串转化为对象
*
* @param json
* @param clazz
* @param <T>
* @return
*/
public static <T> T parse(@NonNull String json, Class<T> clazz) {
T t = null;
try {
t = mapper.readValue(json, clazz);
} catch (Exception e) {
return null;
}
return t;
}
}
05-17
293
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)