admin
2024-07-25 47e3087067abd35e6337c011f96d2338c0bb1aae
src/main/java/org/yeshi/utils/annotation/MapUtil.java
@@ -1,5 +1,10 @@
package org.yeshi.utils.annotation;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.yeshi.utils.StringUtil;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Properties;
@@ -33,4 +38,29 @@
      return target;
   }
    public static Object parseMapByJson(Class<?> clazz, Properties ps, String encoding) {
        if (StringUtil.isNullOrEmpty(encoding)) {
            encoding = "ISO-8859-1";
        }
        JSONObject json = new JSONObject();
        Field[] fields = clazz.getDeclaredFields();
        for (Field fd : fields) {
            fd.setAccessible(true);
            Annotation[] as = fd.getAnnotations();
            for (Annotation a : as) {
                if (a instanceof Map) {
                    Map c = (Map) a;
                    try {
                        json.put(fd.getName(), new String(ps.getProperty(c.value()).getBytes(encoding), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return new Gson().fromJson(json.toString(), clazz);
    }
}