| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- package easydo.technology.utils;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.baomidou.mybatisplus.annotation.TableField;
- import easydo.technology.annotation.NotTableField;
- import java.lang.reflect.Field;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * map工具类
- *
- *
- * @author whz 2020-12-25
- */
- public class MapUtil {
- /**
- * map转List
- */
- public static <T> List<T> mapToList(Map<String, Object> map, Class<T> clazz, String key) {
- List<T> t = null;
- JSONObject jsonObject = mapToJson(map);
- JSONArray array = jsonObject.getJSONArray(key);
- t = array.toJavaList(clazz);
- return t;
- }
- /**
- * map转Json
- */
- public static JSONObject mapToJson(Map<String, Object> map) {
- String data = JSON.toJSONString(map);
- return JSON.parseObject(data);
- }
- /**
- * map中取key对应的value
- *
- * @param map
- * @param key
- * @return
- */
- public static String mapToString(Map<String, Object> map, String key) {
- JSONObject jsonObject = mapToJson(map);
- return jsonObject.getString(key);
- }
- /**
- * map中取类对象
- *
- * @param map
- * @param clazz
- * @param key
- * @param <T>
- * @return
- */
- public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz, String key) {
- T t = null;
- JSONObject jsonObject = mapToJson(map);
- JSONObject object = jsonObject.getJSONObject(key);
- t = object.toJavaObject(clazz);
- return t;
- }
- public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
- T t = null;
- JSONObject jsonObject = mapToJson(map);
- t = jsonObject.toJavaObject(clazz);
- return t;
- }
- /**
- * 对象转化为Map
- *
- * @param obj
- * @return
- * @throws Exception
- */
- public static Map<String, Object> objectToMap(Object obj) throws Exception {
- if (obj == null) {
- return new HashMap<>();
- }
- Map<String, Object> map = new HashMap<>();
- Field[] declaredFields = obj.getClass().getDeclaredFields();
- for (Field field : declaredFields) {
- if ("folders".equals(field.getName()) || "serialVersionUID".equals(field.getName())) {
- continue;
- }
- if (field.isAnnotationPresent(NotTableField.class)) {
- continue;
- }
- if (field.isAnnotationPresent(TableField.class)) {
- if (!field.getAnnotation(TableField.class).exist()) {
- continue;
- }
- }
- field.setAccessible(true);
- if (StringUtil.isEmpty(field.get(obj))) {
- continue;
- }
- map.put(field.getName(), field.get(obj));
- }
- return map;
- }
- }
|