欢迎到我的博客。error0博客代码直接复制过来。格式很乱。让我们来看看。要求字段保持原样,但是fastjson默认是get方法获取字段,首字母转小写。解决方法:1.添加实例化配置JSON.toJSONString(需要实例化的对象,newSerializeConfig(true))//设置为true将字段作为jsonkey传递,默认为flase原理:注:代码省略大致为在第1821行packagecom.alibaba.fastjson.util;publicclassTypeUtils{publicstaticSerializeBeanInfobuildBeanInfo(Class>beanType//,MapaliasMap//,PropertyNamingStrategypropertyNamingStrategy//,booleanfieldBased//){ListfieldInfoList=fieldBased//通过SerializeConfig方法设置fieldBased字段影响如何获取字段?computeGettersWithFieldBase(beanType,aliasMap,false,propertyNamingStrategy):computeGetters(beanType,jsonType,aliasMap,fieldCacheMap,false,propertyNamingStrategy);}}computeGettersWithFieldBase方法大概是这样的Field[]fields=currentClass.getDeclaredFields();computeFields(currentClass,aliasMap,ppropertyNamingStrategy、fieldInfoMap、字段);//Annotationspreferredtogetannotationfields2、fields加@JSONField(name="字段名")原理:computeGetters方法使用过去的get方法作为json的key注:代码省略大致在2015行publicstaticListcomputeGetters(Class>clazz,//JSONTypejsonType,//MapaliasMap,//MapfieldCacheMap,//布尔排序,//PropertyNamingStrategypropertyNamingStrategy//){charc3=方法名.charAt(3);字符串属性名;字段字段=空;if(Character.isUpperCase(c3)//||c3>512//对于unicode方法名称){if(compatibleWithJavaBean){propertyName=decapitalize(methodName.substring(3));//去掉'get'并将首字母转为小写}原理:但是加上@JSONField注解会优先使用注解字段作为key注意:大致相同如上面第2066行方法JSONFieldfieldAnnotation=null;if(field!=null){fieldAnnotation=TypeUtils.getAnnotation(field,JSONField.class);if(fieldAnnotation!=null){if(!fieldAnnotation.serialize()){继续;}ordinal=fieldAnnotation.ordinal();serialzeFeatures=SerializerFeature.of(fieldAnnotation.serialzeFeatures());parserFeatures=Feature.of(fieldAnnotation.parseFeatures());if(fieldAnnotation.name().length()!=0){fieldAnnotationAndNameExists=true;propertyName=fieldAnnotation.name();//获取注解的name属性if(aliasMap!=null){propertyName=aliasMap.get(propertyName);如果(propertyName==null){继续;}}}3.get方法加@JSONField(name="字段名")方法和字段也会优先