fastJson对象转字符串首字母小写问题

特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处: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}

4、参考网站

http://bbs.csdn.net/topics/391831831

原文地址:https://www.cnblogs.com/mao2080/p/6909160.html