部分业务场景在传输数据时,需要的数据格式是扁平化的json格式,而在java对象中有时候为了解耦会做一些嵌套(即对象中包含对象,多层也是常有)。下面的代码可以提供该能力
处理单个对象:ObjectToMapUtil.nestedObj2Map
处理列表对象:ObjectToMapUtil.nestedObjList2ListMap
package cn.sto.station.twin.common.util;
import cn.sto.station.twin.common.util.json.JsonUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 基于反射,将obj转为map
*
* @date 2022-05-30 10:50
*/
@Slf4j
public class ObjectToMapUtil {
private static final String SEPARATOR = "_";
/**
* 嵌套对象转大map(扁平化)
*
* @param object 源对象
* @return map
*/
public static Map<String, Object> nestedObj2Map(Object object) {
Map<String, Object> maps = JSON.parseObject(JSON.toJSONString(object), Map.class);
Map<String, Object> result = new HashMap<>();
maps.forEach((key, value) -> {
common(maps, result, key, value, key);
});
return result;
}
/**
* List嵌套对象转大list map(扁平化)
*
* @param objectList 源List对象
* @return map
*/
public static <T> List<Map<String, Object>> nestedObjList2ListMap(List<T> objectList) {
ArrayList<Map<String, Object>> resultList = new ArrayList<>();
for (T t : objectList) {
resultList.add(nestedObj2Map(t));
}
return resultList;
}
public static Map<String, Object> nestedObj2Map(Map<String, Object> maps, String prefix) {
Map<String, Object> result = new HashMap<>();
String keyPrefix = prefix + SEPARATOR;
maps.forEach((key, value) -> {
String newKey = keyPrefix + key;
common(maps, result, key, value, newKey);
});
return result;
}
public static void common(Map<String, Object> maps, Map<String, Object> result, String key, Object value, String newKey) {
if (maps.get(key) != null && value instanceof JSONObject) {
Map<String, Object> subMaps = (Map) maps.get(key);
Map<String, Object> map = nestedObj2Map(subMaps, newKey);
if (map != null && !map.isEmpty()) {
result.putAll(map);
}
} else {
result.put(newKey, maps.get(key));
}
}
}