1. 将json字符串转成Map:
public static Map jsonToMap(String json) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readValue(json, Map.class);
} catch (IOException e) {
LogUtil.outPutLog(Constant.LOG_ERROR, JsonUtils.class.getSimpleName(), e);
}
return null;
}
2. 将json字符串转换成java对象:
public static <T> T jsonToObject(String json, Class<T> clazz) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return (T) objectMapper.readValue(json, clazz);
} catch (Exception e) {
LogUtil.outPutLog(Constant.LOG_ERROR, JsonUtils.class.getSimpleName(), e);
}
return null;
}
3. 将Java对象转换成Josn:
public static String objectToJsonString(Object obj) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(obj);
} catch (Exception e) {
LogUtil.outPutLog(Constant.LOG_ERROR, JsonUtils.class.getSimpleName(), e);
}
return null;
}
4. 序列化、反序列化时忽略不必要的属性:
序列化时可以在成员变量上面加入@JsonIgnore注解:
@JsonInclude(content = Include.NON_NULL, value = Include.NON_NULL)
private String test;
@JsonInclude(content = Include.NON_EMPTY, value = Include.NON_EMPTY)
private List<Available> vehicle = new ArrayList<Available>();
反序列化时可以直接在类上面加入@JsonIgnoreProperties,忽略所有未知属性,也可以单个去忽略
@JsonIgnoreProperties(ignoreUnknown = true)
public class TestObject {...}