欢送来我的博客逛逛 error0 Blog
代码是间接复制过去,格局比拟乱大家对付看一下吧
需要要保留字段原样,可 fastjson 默认是获取 get 办法的字段并把首字母转成小写。
解决方案:
1、增加实例化配置
JSON.toJSONString(须要实例化的对象,new SerializeConfig(true)) // 设置 true 通过字段作为 json key, 默认为 flase
注:代码省略 大抵在 1821 行
package com.alibaba.fastjson.util;
public class TypeUtils{
public static SerializeBeanInfo buildBeanInfo(Class<?> beanType //
, Map<String,String> aliasMap //
, PropertyNamingStrategy propertyNamingStrategy //
, boolean fieldBased //
){
List<FieldInfo> fieldInfoList = fieldBased // 通过 SerializeConfig 办法设置 fieldBased 这个字段影响了如何获取字段
? computeGettersWithFieldBase(beanType, aliasMap, false, propertyNamingStrategy)
: computeGetters(beanType, jsonType, aliasMap, fieldCacheMap, false, propertyNamingStrategy);
}
}
computeGettersWithFieldBase 办法大略是这样
Field[] fields = currentClass.getDeclaredFields();
computeFields(currentClass, aliasMap, propertyNamingStrategy, fieldInfoMap, fields); // 有注解优先获取注解字段
2、字段加上 @JSONField(name=” 字段名称 ”)
computeGetters 办法是通过过来 get 办法作为 json 的 key
注:代码省略 大抵在 2015 行
public static List<FieldInfo> computeGetters(Class<?> clazz, //
JSONType jsonType, //
Map<String,String> aliasMap, //
Map<String,Field> fieldCacheMap, //
boolean sorted, //
PropertyNamingStrategy propertyNamingStrategy //
){char c3 = methodName.charAt(3);
String propertyName;
Field field = null;
if(Character.isUpperCase(c3) //
|| c3 > 512 // for unicode method name
){if(compatibleWithJavaBean){propertyName = decapitalize(methodName.substring(3));// 去掉‘get’并转首字母小写
}
然而加上 @JSONField 注解会优先应用注解字段为 key
注:大抵在 2066 行 同上办法
JSONField fieldAnnotation = null;
if(field != null){fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class);
if(fieldAnnotation != null){if(!fieldAnnotation.serialize()){continue;}
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);
if(propertyName == null){continue;}
}
}