1.情景展示
如上圖所示,我想要將枚舉類轉換成json對象,key對應屬性名稱,value對應屬性值,效果如下:
{"IvcVoucherCode":"200","IvcVoucherStatus":"票據模板下載成功"}
如何實現?
2.代碼實現
思路:使用spring的org.springframework.beans.BeanWrapperImpl對對象的拆解
所需jar包:
<!--枚舉類轉json對象--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.7.RELEASE</version> </dependency>
具體代碼:
/* * 枚舉類轉換為json對象 * @attention: * @date: 2020年11月17日 0017 14:44 * @param: anEnum * @param: initialUpper key的首字母是否大寫 * true:大寫,false:小寫 * @return: com.alibaba.fastjson.JSONObject */ public static com.alibaba.fastjson.JSONObject fromEum(Enum anEnum, boolean initialUpper){ com.alibaba.fastjson.JSONObject aliJson = new com.alibaba.fastjson.JSONObject(); if(anEnum == null) return null; // json.put("enumName",anEnum.name()); BeanWrapper src = new BeanWrapperImpl(anEnum); PropertyDescriptor[] pds = src.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { String key = pd.getName(); // 執行新一輪循環,不添加到json中 if("class".equals(key) || "declaringClass".equals(key)){ continue; } if (initialUpper) { aliJson.put(StringUtils.convertInitialUpper(key),src.getPropertyValue(key)); } else { aliJson.put(key,src.getPropertyValue(key)); } } log.debug("枚舉轉json對象前:" + anEnum.toString()); log.debug("枚舉轉json對象后:" + aliJson); return aliJson; }
由於枚舉的成員變量名稱,首字母都是大寫,而使用BeanWrapper后,首字母會被轉成小寫,所以我增加了對於大寫的支持。
關於首字母轉大寫的代碼,見文末推薦
3.測試