json解析之jackson ObjectMapper

时间:2022-08-20 16:27:14

Json解析常用的有fastjson和jackson,性能上网上有不少的对比,说是fastjson比较好,今天先整理一下jackson的东西,后面再发一个fastjson的。

jackson是spring mvc内置的json转换工具,fastjson则是阿里做的开源工具包。

jackson序列化如下:

 /**
* json serialize
* @param obj
* @return
*/
public static String jsonSerialize(final Object obj) {
ObjectMapper om = new ObjectMapper();
try {
return om.writeValueAsString(obj);
} catch (Exception ex) {
return null;
}
}

jackson反序列化如下:

 /**
* json deserialize
* @param json
* @param mapClazz
* @return
*/
public static Object jsonDeserialize(final String json, final Class<?> mapClazz) {
ObjectMapper om = new ObjectMapper();
try {
return om.readValue(json, mapClazz);
} catch (Exception ex) {
return null;
}
}

在使用的过程中,很有可能会遇到json反序列化的问题。当你对象中有get***()的地方,它就当做它是一个属性,所以当你序列化json之后,在反序列化的时候,很有可能会出现异常的情况,因为在你的model中没有这个***的定义。

那该如何处理和解决呢?

jackson给出了它自己的解决方案(JacksonHowToIgnoreUnknow):

1. 在class上添加忽略未知属性的声明:@JsonIgnoreProperties(ignoreUnknown=true)

2. 在反序列化中添加忽略未知属性解析,如下:

 /**
* json deserialize
* @param json
* @param mapClazz
* @return
*/
public static Object jsonDeserialize(final String json, final Class<?> mapClazz) {
ObjectMapper om = new ObjectMapper();
try {
// 忽略未知属性
om.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return om.readValue(json, mapClazz);
} catch (Exception ex) {
return null;
}
}

3. 添加"Any setter"来处理未知属性

 // note: name does not matter; never auto-detected, need to annotate
// (also note that formal argument type #1 must be "String"; second one is usually
// "Object", but can be something else -- as long as JSON can be bound to that type)
@JsonAnySetter
public void handleUnknown(String key, Object value) {
// do something: put to a Map; log a warning, whatever
}

4. 注册问题处理句柄

注册一个DeserializationProblemHandler句柄,来调用ObjectMapper.addHandler()。当添加的时候,句柄的handleUnknownProperty方法可以在每一个未知属性上调用一次。

这个方法在你想要添加一个未知属性处理日志的时候非常有用:当属性不确定的时候,不会引起一个绑定属性的错误。