1、问题
使用Fastjson转json之后发现首字母小写。实体类如下:
@Data
public class DataIdentity {
private String BYDBSM;
private String SNWRSSJSJ;
private Integer CJFS = 20;
}
测试代码如下:
public static void main(String[] args) {
DataIdentity dataIdentity = new DataIdentity();
dataIdentity.setBYDBSM("xxx");
dataIdentity.setSNWRSSJSJ(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
String str = JSON.toJSONString(dataIdentity);
System.out.println(str);
}
测试结果如下:
![]()
2、分析
通过查看Fastjson源码可知,Fatjson在序列化对象时,会判断compatibleWithJavaBean,如果为false则将首字母小写,compatibleWithJavaBean默认值为false.
public 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);
...
3、解决方案
1.compatibleWithJavaBean设置为true
TypeUtils.compatibleWithJavaBean = true;
也可以通过设置jvm参数。
2.@JSONField注解
@Data
public class DataIdentity {
@JSONField(name = "BYDBSM")
private String BYDBSM;
@JSONField(name = "SNWRSSJSJ")
private String SNWRSSJSJ;
@JSONField(name = "CJFS")
private Integer CJFS = 20;
}
![]()
3、使用hutool的JSONUtil.toJsonStr()方法
String str = JSONUtil.toJsonStr(yytStuCountDto);
4、参考文章
Fastjson首字母大小写问题_fastjson 首字母小写-CSDN博客
https://www.cnblogs.com/haoxianrui/p/12853343.html
fastjson转换json时,碰到的那些首字母大小写转换的坑! - 简书









![[数据结构] 排序#插入排序希尔排序](https://i-blog.csdnimg.cn/direct/570343accdbd428bb9d9948693d69c05.png)




![[FreeRTOS 功能应用] 互斥量 功能应用](https://i-blog.csdnimg.cn/direct/9e9f8c31a549452298de10935da1e7ce.png)




