fastJson Gson对比及java序列化问题

 

一个案例

POJO没有set方法, 造成反序列化时出现NPE问题。实际场景:POJO是第三方提供的,final

 1 public class XJSONTest {
 2 
 3     public static void main(String[] args) {
 4         String inStr = "{\"isSuccess\":true}";
 5 
 6         // Google Gson
 7         Gson gson = new Gson();
 8         Result result = gson.fromJson(inStr, Result.class);
 9         System.out.println(result.getIsSuccess());
10 
11         //alibaba FastJson
12         Result result2 = JSON.parseObject(inStr, Result.class);
13         System.out.println(result2.getIsSuccess());
14     }
15 }
16 
17 class Result {
18     Boolean isSuccess;
19 
20     public Boolean getIsSuccess() {
21         return isSuccess;
22     }
23 }

运行结果:Gson的输出true, FastJson输出null,   后面的业务逻辑使用getIsSuccess时很容易出现NPE

FastJson坑真多, 上次遇到一个byte[]数组自动base64编码,还有各种安全问题, 。。。

 

原因分析:

Gson序列化时直接操作field, FastJson操作的是get set方法

RPC框架中的序列化: Hession也是操作field

 

posted @ 2018-08-03 10:18  funny_coding  阅读(694)  评论(0编辑  收藏  举报
build beautiful things, share happiness