对象与JSON之间的互转
程序员文章站
2024-03-18 18:42:10
...
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 对象与JSON之间的互转
*/
public class JsonUtils {
//转换JSOn的对象
private static ObjectMapper om = new ObjectMapper();
static{
om.setSerializationInclusion(Include.NON_NULL);
}
//对象转JSON格式字符串
public static String getObjectToJson(Object obj){
try {
return om.writeValueAsString(obj);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//JSON格式的字符串转成对象
public static <T> T getJsonToObject(String json, Class<T> beanType){
T t = null;
try {
t = om.readValue(json, beanType);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
}
上一篇: Java小结