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
博客讲述了在项目中遇到Fastjson替换org.json后,由于Fastjson默认将首字母转换为小写导致的问题。文章提供了两种解决方法:1) 设置`compatibleWithJavaBean`为true;2) 使用`@JSONField`注解指定字段名称。通过分析Fastjson源码,了解到此行为是由于`compatibleWithJavaBean`默认为false引起的。
1488

被折叠的 条评论
为什么被折叠?



