JSON和对象之间相互转换
当我们用HttpClient在程序内部发起跨域请求或者在用redis做缓存的的存值和取值的时候,都需要将pojo对象转化成JSON串或者JSON串转对象来实现各种各种需求,同过JSON提供的一些方法封装可以简化一些代码量.在这里插入代码片
public class ObjectMapperUtil {
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 对象转化为json
*/
public static String toJSON(Object target) {
String result = null;
try {
result = MAPPER.writeValueAsString(target);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return result;
}
//JSON串转化pojo对象
public static <T> T toObject(String json,Class<T> targetClass) {
T object = null;
try {
object = MAPPER.readValue(json, targetClass);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
return object;
}
}