java嵌套对象转大map(扁平化)

        部分业务场景在传输数据时,需要的数据格式是扁平化的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));
        }
    }

    

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值