0 概述
本文主要讲述在实际工作中遇到的fastjson(版本1.2.34)相关问题。
1 常见问题
1.1缺少默认的构造函数
使用JSON形式的序列化技术时,所有通信传递的对象必须设置无参的默认构造函数。
public@H_403_12@ class@H_403_12@ User {
private@H_403_12@ String name;
private@H_403_12@ int@H_403_12@ age;
public@H_403_12@ User@H_403_12@(String name,int@H_403_12@ age) {
this@H_403_12@.name = name;
this@H_403_12@.age = age;
}
public@H_403_12@ String getName@H_403_12@() {
return@H_403_12@ name;
}
public@H_403_12@ void@H_403_12@ setName@H_403_12@(String name) {
this@H_403_12@.name = name;
}
public@H_403_12@ int@H_403_12@ getAge@H_403_12@() {
return@H_403_12@ age;
}
public@H_403_12@ void@H_403_12@ setAge@H_403_12@(int@H_403_12@ age) {
this@H_403_12@.age = age;
}
public@H_403_12@ class@H_403_12@ JsonTest {
public@H_403_12@ static@H_403_12@ void@H_403_12@ main@H_403_12@(String[] args) {
System.out@H_403_12@.println(JSON.parSEObject("{\"name\":\"test\",\"age\":12}\n"@H_403_12@,User.class));
}
}
Exception in@H_403_12@ thread "main"@H_403_12@ com.alibaba.fastjson.JSONException: default constructor not found
...@H_403_12@
1.2 序列化或反序列化结果不对
fastjson默认根据get和set方法来生成json体中的属性键值对,如果实体属性中没有对应的set或get方法将得不到结果。
public@H_403_12@ class@H_403_12@ User {
private@H_403_12@ String name;
private@H_403_12@ int@H_403_12@ age;
public@H_403_12@ User@H_403_12@(String name,int@H_403_12@ age) {
this@H_403_12@.name = name;
this@H_403_12@.age = age;
}
public@H_403_12@ User@H_403_12@() {
}
public@H_403_12@ String getName@H_403_12@() {
return@H_403_12@ name;
}
public@H_403_12@ void@H_403_12@ setName@H_403_12@(String name) {
this@H_403_12@.name = name;
}
@Override
public@H_403_12@ String toString@H_403_12@() {
return@H_403_12@ "User{"@H_403_12@ +
"name='"@H_403_12@ + name + '\''@H_403_12@ +
",age="@H_403_12@ + age +
'}'@H_403_12@;
}
}
public@H_403_12@ class@H_403_12@ JsonTest {
public@H_403_12@ static@H_403_12@ void@H_403_12@ main@H_403_12@(String[] args) {
System.out@H_403_12@.println(JSON.toJSON(new@H_403_12@ User("test"@H_403_12@,12@H_403_12@)));
System.out@H_403_12@.println(JSON.parSEObject("{\"name\":\"test\",User.class));
}
}
由于age属性没有get方法,序列化时候就没有age信息,反序列化也类似 输出: {“name”:”test”} User{name=’test’,age=0}