1. 程式人生 > >FastJson 輸出值 首字母大小寫問題

FastJson 輸出值 首字母大小寫問題

解決方案:

1. 如果你的專案由多個模組且為分散式部署, 則可考慮使用設定System.property

2. 一般只是極少數的程式碼出現此情況, 那麼建議直接在你的單例Service初始化時, 在靜態塊中直接改變TypeUtils的變數值, 如果用Spring的話可以使用InitializingBean進行處理

TypeUtils.compatibleWithJavaBean = true;

3. 此變數是public的注意要在一個地方進行改動, 避免執行緒安全問題

專案組使用FastJson, 在輸出下面一段Json的時候出現此問題, 期望是大寫但是fastJson將值自動首字母變成小寫了

{"code":0,"message":"","result":{"facts":{"ip":{"aCUN_ONE_MIN":0,"aCUN_TEN_MIN":0}},"level":0}}

查詢後發現fastjson內部做Bean轉換時會使用到 com.alibaba.fastjson.util.TypeUtils, 核心程式碼如下, 在類載入的時候會去讀取環境變數 fastjson.compatibleWithJavaBean, 找不到則使用預設值false,將會導致首字母小寫

複製程式碼
public static boolean compatibleWithJavaBean = false;

    
static { try { String prop = System.getProperty("fastjson.compatibleWithJavaBean"); if ("true".equals(prop)) { compatibleWithJavaBean = true; } else if ("false".equals(prop)) { compatibleWithJavaBean = false; } }
catch (Throwable ex) { // skip } } public static List<FieldInfo> computeGetters(Class<?> clazz, Map<String, String> aliasMap, boolean sorted) {

String propertyName;
if (Character.isUpperCase(c3)) {
if (compatibleWithJavaBean) {
propertyName = Introspector.decapitalize(methodName.substring(3));
} else {
propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
}
} else if (c3 == '_') {
propertyName = methodName.substring(4);
} else if (c3 == 'f') {
propertyName = methodName.substring(3);
} else {
continue;
}}

複製程式碼