[size=large][b]一.jackson一般的使用默认的配置:[/b][/size]
[b]1.json字符串转化为对应的java类[/b]
[b]2.java类转化为json字符串[/b]
[size=large][b]二.一些我用到的配置[/b][/size]
[b]1.对于json字符串转java对象[/b]
除了DeserializationFeature,还可以设置SerializationFeature也就是序列化的属性
[b]1.json字符串转化为对应的java类[/b]
public static <T> T transferToObj(String jsonString, Class<T> valueType) {
if (StringUtil.isBlank(jsonString)) {
throw new IllegalArgumentException(
"[Assertion failed] - the object argument must be blank");
}
T value = null;
try {
ObjectMapper mapper = new ObjectMapper();
value = mapper.readValue(jsonString, valueType);
} catch (JsonParseException e) {
ExceptionUtil.caught(e, "jsonString=[" + jsonString + "]");
} catch (JsonMappingException e) {
ExceptionUtil.caught(e, "jsonString=[" + jsonString + "]");
} catch (IOException e) {
ExceptionUtil.caught(e, "jsonString=[" + jsonString + "]");
}
return value;
}
[b]2.java类转化为json字符串[/b]
public static <T> String transfer2JsonString(T value) {
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
JsonGenerator gen;
try {
gen = new JsonFactory().createGenerator(sw);
mapper.writeValue(gen, value);
gen.close();
} catch (IOException e) {
ExceptionUtil.caught(e, "value=[" + value + "]");
}
return sw.toString();
}
[size=large][b]二.一些我用到的配置[/b][/size]
[b]1.对于json字符串转java对象[/b]
......
ObjectMapper mapper = new ObjectMapper();
//在反序列化的时候,如果不识别的字段忽略
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//反序列化时候,如果json串中的字段出现String("")或者null的就把java对应属性设置为Null
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
value = mapper.readValue(jsonString, valueType);
..........
除了DeserializationFeature,还可以设置SerializationFeature也就是序列化的属性