package thyyxxk.webserver.utils;


import com.alibaba.fastjson.JSON;

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 {
        StringBuilder buffer = new StringBuilder("[");
        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("\"").append(name.substring(0, 1).toLowerCase()).append(name.substring(1)).append("\":\"");
                    buffer.append(method.invoke(obj)).append("\"");
                }
            }
            buffer.append("}");
        }
        buffer.append("]");
        return JSON.parseArray(buffer.toString());
    }

}
