今天遇到一个问题,修改一个javaBean的字段后,fastJson转换成JsonString的时候字段却没有被修改,而Gson是正常的。
JavaBean如下:
public class DistrictInfo {
private String province;
private String city;
private String dist;
public DistrictInfo() {
super();
}
public DistrictInfo(String province,String city,String district) {
super();
this.province = province;
this.city = city;
this.dist = district;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDistrict() {
return dist;
}
public void setDistrict(String district) {
this.dist = district;
}
@Override
public String toString() {
return province + "," + city;
}
}
测试类如下:
public class testJson {
public static void main(String[] args) {
DistrictInfo district = new DistrictInfo("陕西省","宝鸡市","陈仓区");
System.out.println("FastJson: " + JSON.toJSONString(district,true));
System.out.println("Gson: " + new Gson().toJson(district));
}
}
运行结果如下:
FastJson: {
"city":"宝鸡市","district":"陈仓区","province":"陕西省"
}
Gson: {"province":"陕西省","city":"宝鸡市","dist":"陈仓区"}
可以看到对District字段,两者解析是不同的,FastJson是错的。其实,这是FastJson的反射机制有缺陷引起的,将修饰符改为Public之后就可以正常解析了。
public class DistrictInfo {
public String province;
public String city;
public String dist;
public DistrictInfo() {
super();
}
public DistrictInfo(String province,String district) {
super();
this.province = province;
this.city = city;
this.dist = district;
}
}
结果:
FastJson: {
"city":"宝鸡市","dist":"陈仓区","province":"陕西省"
}
Gson: {"province":"陕西省","dist":"陈仓区"}
如果修饰符为Protected/Private,fastJson走了一种曲线救国的方式,通过Public的getXXX()方法来获得该字段的名称和值。所以必须要保证getXXX()方法与字段XXX保持一致。如下:
public class DistrictInfo {
private String province;
private String city;
private String dist;
public DistrictInfo() {
super();
}
public DistrictInfo(String province,String district) {
super();
this.province = province;
this.city = city;
this.dist = district;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDist() {
return dist;
}
public void setDist(String dist) {
this.dist = dist;
}
@Override
public String toString() {
return province + "," + city;
}
}
结果
FastJson: {
"city":"宝鸡市","dist":"陈仓区"}
结论: fastJson在将JsonString2Obj的速度和便捷性上优于Gson,但是在Obj2JsonString时需要注意如果字段不是public的,需要注意保证getXXX()方法与字段XXX保持一致。,