Fastjson首字母大小写问题
最近由于项目里用到了多个json类库,fastjson,org.json,jackson都有用到,最终把json类库统一成了API最为简单的Fastjson。
Fastjson替换org.json之后导致部分功能不可用,最终确定为fastjson的默认首字母小写机制造成的。
maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
测试代码
// 省略get set
public class Student {
private String ID;
private String NAME;
private String ADDREDD;
}
测试代码
import com.alibaba.fastjson.JSON;
public class FastjsonTest {
public static void main(String[] args) {
Student student = new Student();
student.setID("123");
student.setNAME("zhangsan");
student.setADDREDD("shanghai");
String s = JSON.toJSONString(student);
System.out.println(s);
}
}
{"aDDREDD":"shanghai","iD":"123","nAME":"zhangsan"}
解决办法
1.compatibleWithJavaBean设置为true
TypeUtils.compatibleWithJavaBean = true;
也可以通过设置jvm参数。
2.@JSONField注解
public class Student {
@JSONField(name = "ID")
private String ID;
@JSONField(name="NAMW")
private String NAME;
@JSONField(name = "ADDRESS")
private String ADDREDD;
}
{"ADDRESS":"shanghai","ID":"123","NAMW":"zhangsan"}
问题分析
通过查看Fastjson源码可知,Fatjson在序列化对象时,会判断compatibleWithJavaBean,如果为fals则将首字母小写,compatibleWithJavaBean默认值为false.
ublic class TypeUtils {
private static final Pattern NUMBER_WITH_TRAILING_ZEROS_PATTERN = Pattern.compile("\\.0*$");
public static boolean compatibleWithJavaBean = false;
public static boolean compatibleWithFieldName = false;
...
}
...
if (Character.isUpperCase(c2)) {
if (compatibleWithJavaBean) {
propertyName = decapitalize(methodName.substring(2));
} else {
propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3);
}
propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 2);
...
参考资料
https://github.com/alibaba/fastjson/issues/373