EnumToJson.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package thyyxxk.webserver.utils;
  2. import com.alibaba.fastjson.JSON;
  3. import thyyxxk.webserver.constants.RestrictedDrugLevels;
  4. import thyyxxk.webserver.constants.Ysjb;
  5. import java.lang.reflect.InvocationTargetException;
  6. import java.lang.reflect.Method;
  7. public class EnumToJson {
  8. /**
  9. * 通过反射机制,将枚举值转化为json串
  10. *
  11. * @param enumValues
  12. * @return
  13. * @throws IllegalAccessException
  14. * @throws InvocationTargetException
  15. */
  16. public static JSON toJson(Enum<?>[] enumValues) throws IllegalAccessException, InvocationTargetException {
  17. StringBuffer buffer = new StringBuffer("[");
  18. boolean obj1st = true;
  19. for (Object obj : enumValues) {
  20. if (obj1st) {
  21. obj1st = false;
  22. } else {
  23. buffer.append(",");
  24. }
  25. buffer.append("{");
  26. Method[] methods = obj.getClass().getMethods();
  27. boolean method1st = true;
  28. for (Method method : methods) {
  29. //获取枚举值的get方法
  30. if (method.getName().startsWith("get") && method.getParameterTypes().length == 0 && !method.getName().contains("Class")) {
  31. //处理逗号
  32. if (method1st) {
  33. method1st = false;
  34. } else {
  35. buffer.append(",");
  36. }
  37. //将get方法的get去掉,并且首字母小写
  38. String name = method.getName().replace("get", "");
  39. buffer.append("\"" + name.substring(0, 1).toLowerCase() + name.substring(1) + "\":\"");
  40. buffer.append(method.invoke(obj) + "\"");
  41. }
  42. }
  43. buffer.append("}");
  44. }
  45. buffer.append("]");
  46. return JSON.parseArray(buffer.toString());
  47. }
  48. public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
  49. System.out.println(toJson(RestrictedDrugLevels.values()));
  50. System.out.println(toJson(Ysjb.values()));
  51. }
  52. }