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


http://www.cnblogs.com/zhwbqd/p/3976697.html

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;
}}

複製代碼

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章