结论:
1.fastjson和jackJson:在把对象序列化成字符串的时候,是通过反射遍历该类中的所有的getter方法,通过getXX或者isXX ,然后根据JavaBeans规则-> 得到属性名称,XX,然后直接序列化为字符串。
2.Gson:在把对象序列化成字符串的时候,他是通过反射遍历该类中的所有属性,并把其值序列化成json字符串的
补充:
根据JavaBeans Specification规定,如果是普通的参数propertyName,要以以下方式定义其setter/getter:
public <PropertyType> get<PropertyName>();
public void set<PropertyName>(<PropertyType> a);
但是,布尔类型的变量propertyName则是单独定义的:
public boolean is<PropertyName>();
public void set<PropertyName>(boolean m);
success方法的 getter 应该是isSuccess/getSuccess,而isSuccess的getter 应该是isIsSuccess/getIsSuccess。
例子:
public class Model implements Serializable {
private static final long serialVersionUID = 1836697963736227954L;
private Boolean isSuccess;
public Boolean isSuccess() {
return isSuccess;
}
public void setSuccess(Boolean success) {
isSuccess = success;
}
public String getHollis(){
return "hollischuang";
}
}
public class SerializeTest {
public static void main(String[] args) throws JsonProcessingException {
serializeTest();
System.out.println("=================================");
deSerializeTest();
}
public static void serializeTest() throws JsonProcessingException {
Model model = new Model();
model.setSuccess(true);
//使用fastjson(1.2.16)序列化model成字符串并输出
System.out.println("Serializable Result With fastjson :" + JSON.toJSONString(model));
//使用Gson(2.8.5)序列化model成字符串并输出
Gson gson =new Gson();
System.out.println("Serializable Result With Gson :" +gson.toJson(model));
//使用jackson(2.9.7)序列化model成字符串并输出
ObjectMapper om = new ObjectMapper();
System.out.println("Serializable Result With jackson :" +om.writeValueAsString(model));
}
public static void deSerializeTest(){
Model model = new Model();
model.setSuccess(true);
Gson gson = new Gson();
Model mode = gson.fromJson(JSON.toJSONString(model), Model.class);
System.out.println(gson.toJson(mode));
}
}
注意:Boolean值的属性取名时,慎用is开头,避免踩坑。