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.测试
