特別提示:本人博客部分有參考網絡其他博客,但均是本人親手編寫過並驗證通過。如發現博客有錯誤,請及時提出以免誤導其他人,謝謝!歡迎轉載,但記得標明文章出處: 
          http://www.cnblogs.com/mao2080/ 
         
 
         1、問題描述
最近在做接口,對方提供的接口文檔里面屬性居然都是大寫的,感覺搞的很不專業。最大的問題是:轉化為json字符串的時候自動把首字母給轉為小寫了。
2、解決方法
在字段的get方法上添加@JSONField(name = "NAME") 注解可以解決這類問題,具體代碼如下:
1 package com.mao.beans; 2 3 import com.alibaba.fastjson.JSON; 4 import com.alibaba.fastjson.annotation.JSONField; 5 import com.alibaba.fastjson.serializer.SerializerFeature; 6 7 public class T { 8 9 public static void main(String[] args) throws Exception { 10 String s = toJson(new User()); 11 System.out.println(s); 12 } 13 14 /** 15 * 16 * 描述:將對象格式化成json字符串 17 * @author mao2080@sina.com 18 * @created 2017年4月1日 下午4:38:18 19 * @since 20 * @param object 對象 21 * @return json字符串 22 * @throws Exception 23 */ 24 public static String toJson(Object object) throws Exception { 25 try { 26 return JSON.toJSONString(object, new SerializerFeature[] { 27 SerializerFeature.WriteMapNullValue, 28 SerializerFeature.DisableCircularReferenceDetect, 29 SerializerFeature.WriteNonStringKeyAsString }); 30 } catch (Exception e) { 31 throw new Exception(e); 32 } 33 } 34 35 } 36 37 class User { 38 39 private String NAME; 40 41 private int AGE; 42 43 @JSONField(name = "NAME") 44 public String getNAME() { 45 return NAME; 46 } 47 48 public void setNAME(String nAME) { 49 NAME = nAME; 50 } 51 52 @JSONField(name = "AGE") 53 public int getAGE() { 54 return AGE; 55 } 56 57 public void setAGE(int aGE) { 58 AGE = aGE; 59 } 60 61 }
3、運行結果
{"AGE":0,"NAME":null} 
        