package thyyxxk.webserver.utils; import com.alibaba.fastjson.JSON; import thyyxxk.webserver.constants.RestrictedDrugLevels; import thyyxxk.webserver.constants.Ysjb; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class EnumToJson { /** * 通过反射机制,将枚举值转化为json串 * * @param enumValues * @return * @throws IllegalAccessException * @throws InvocationTargetException */ public static JSON toJson(Enum[] enumValues) throws IllegalAccessException, InvocationTargetException { StringBuffer buffer = new StringBuffer("["); boolean obj1st = true; for (Object obj : enumValues) { if (obj1st) { obj1st = false; } else { buffer.append(","); } buffer.append("{"); Method[] methods = obj.getClass().getMethods(); boolean method1st = true; for (Method method : methods) { //获取枚举值的get方法 if (method.getName().startsWith("get") && method.getParameterTypes().length == 0 && !method.getName().contains("Class")) { //处理逗号 if (method1st) { method1st = false; } else { buffer.append(","); } //将get方法的get去掉,并且首字母小写 String name = method.getName().replace("get", ""); buffer.append("\"" + name.substring(0, 1).toLowerCase() + name.substring(1) + "\":\""); buffer.append(method.invoke(obj) + "\""); } } buffer.append("}"); } buffer.append("]"); return JSON.parseArray(buffer.toString()); } public static void main(String[] args) throws InvocationTargetException, IllegalAccessException { System.out.println(toJson(RestrictedDrugLevels.values())); System.out.println(toJson(Ysjb.values())); } }