fastjson:对于Exception中复杂类型(enum,...以及自定义类型)成员
如果一个Exception类中有枚举类型或其他复杂类型(比如java.util.Date,或自定义类型)的成员,fastjson反序列化会抛出异常。 // ServiceSecurityException 类型中 type 成员是个枚举类型SecurityExceptionType
ServiceSecurityException exp = new ServiceSecurityException("hello").setType(SecurityExceptionType.INVALID_PERSON_ID).setDeviceID(10);
// 序列化可以正常输出
System.out.println(JSON.toJSONString(exp));
// 反序列化就会抛出异常
JSON.parSEObject(JSON.toJSONString(exp),ServiceSecurityException.class);
抛出的异常如下:
这应该是个bug,(我用版本的是1.2.38,就是支持java7的最后一个版本,再往后的版本都是java8编译的).跟踪了fastjson的源码,发现用于Exception的反序列化的 我解决方法是绕开它,因为是在 步骤1–序列化过程将异常类型中需要序列化的字段序列化成一个简单的json string,这样在反序列化时fastjson就不会把它当做一个异常类型交给 public String toJsonString(ServiceSecurityException exp){
HashMap<String,Object> fields = new HashMap<String,Object>();
fields.put("type",exp.getType());
fields.put("deviceID",exp.getDeviceID());
return JSON.toJSONString(fields);
}
步骤2–反序列化用 步骤3–反序列化用 代码实现如下: String jsonStr = toJsonString(exp); JSONObject obj = JSON.parSEObject(jsonStr); ServiceSecurityException newExp = TypeUtils.castToJavaBean(obj,ServiceSecurityException.class); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |