json解析之jackson ObjectMapper

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

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

jackson序列化如下:

 1 /**
 2  * json serialize
 3  * @param obj
 4  * @return
 5 */
 6 public static String jsonSerialize(final Object obj) {
 7     ObjectMapper om = new ObjectMapper();
 8     try {
 9         return om.writeValueAsString(obj);
10     } catch (Exception ex) {
11         return null;
12     }
13 }

jackson反序列化如下:

 1 /**
 2  * json deserialize
 3  * @param json
 4  * @param mapClazz
 5  * @return
 6 */
 7 public static Object jsonDeserialize(final String json, final Class<?> mapClazz) {
 8     ObjectMapper om = new ObjectMapper();
 9     try {
10         return om.readValue(json, mapClazz);
11     } catch (Exception ex) {
12         return null;
13     }
14 }

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

那该如何处理和解决呢?

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

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

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

 1 /**
 2  * json deserialize
 3  * @param json
 4  * @param mapClazz
 5  * @return
 6 */
 7 public static Object jsonDeserialize(final String json, final Class<?> mapClazz) {
 8     ObjectMapper om = new ObjectMapper();
 9     try {
10         // 忽略未知属性
11         om.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
12         return om.readValue(json, mapClazz);
13     } catch (Exception ex) {
14         return null;
15     }
16 }

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

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

4. 注册问题处理句柄

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

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

转载于:https://my.oschina.net/secyaher/blog/274495

猜你喜欢

转载自blog.csdn.net/weixin_33843947/article/details/91967240