通过反射机制,将枚举类型转化为json.

 

[java] view plain copy
    1. public static String toJson(Enum<?>[] enumValues) throws IllegalAccessException, InvocationTargetException {  
    2.     StringBuffer buffer=new StringBuffer("[");  
    3.     boolean obj1st=true;  
    4.     for (Object obj : enumValues) {  
    5.         if(obj1st){  
    6.             obj1st=false;  
    7.         }else{  
    8.             buffer.append(",");  
    9.         }  
    10.         buffer.append("{");  
    11.   
    12.         Method[] methods = obj.getClass().getMethods();  
    13.         boolean method1st=true;  
    14.         for (int i = 0; i < methods.length; i++) {  
    15.   
    16.             Method method = methods[i];  
    17.             //获取枚举值的get方法  
    18.             if (method.getName().startsWith("get") && method.getParameterTypes().length == 0 && !method.getName().contains("Class")) {  
    19.                 //处理逗号  
    20.                 if(method1st){  
    21.                     method1st=false;  
    22.                 }else{  
    23.                     buffer.append(",");  
    24.                 }  
    25.                 //将get方法的get去掉,并且首字母小写  
    26.                 String name = method.getName().replace("get","");  
    27.                 buffer.append("\"" + name.substring(0, 1).toLowerCase() + name.substring(1) + "\":\"");  
    28.                 buffer.append(method.invoke(obj)+"\"");  
    29.             }  
    30.         }  
    31.         buffer.append("}");  
    32.     }  
    33.     buffer.append("]");  
    34.     return buffer.toString();  
    35. }  
posted @ 2018-05-19 09:48  sundaysios  阅读(104)  评论(0)    收藏  举报