当前位置 : 主页 > 编程语言 > java >

java如何实现嵌套对象转大map(扁平化)

来源:互联网 收集:自由互联 发布时间:2023-01-30
目录 嵌套对象转大map(扁平化) java:JSON扁平化和去扁平化 1、扁平化数据(网上找的一json大串) 2、maven依赖 3、扁平化 4、去扁平化 嵌套对象转大map(扁平化) 部分业务场景在传输数据时,
目录
  • 嵌套对象转大map(扁平化)
  • java:JSON扁平化和去扁平化
    • 1、扁平化数据(网上找的一json大串)
    • 2、maven依赖
    • 3、扁平化
    • 4、去扁平化

嵌套对象转大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));
        }
    }
 
    
 
}

java:JSON扁平化和去扁平化

在github上发现了一个比较好的JSON扁平化和去扁平化处理方法,话不多说,直接开干。

1、扁平化数据(网上找的一json大串)

"{\"type\":10,\"data\":[{\"text\":\"献给爱我们的女神\",\"is_liked\":false,\"index_cover\":\"http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_989_123986672_17737936936133063098.jpg?imageView/2/w/960/q/85\",\"poi\":\"\",\"cover_image_height\":816,\"trip_id\":2387282916,\"index_title\":\"\",\"center_point\":{},\"view_count\":36207,\"location_alias\":\"\",\"cover_image_1600\":\"http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/1384/h/1384/q/85\",\"cover_image_s\":\"http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/1/w/280/h/280/q/75\",\"share_url\":\"btrip/spot/2387842143/\",\"timezone\":\"Asia/Shanghai\",\"date_tour\":\"2016-06-19T01:19:07+08:00\",\"is_hiding_location\":false,\"user\":{\"location_name\":\"\",\"name\":\"丑到没墙角\",\"resident_city_id\":\"\",\"mobile\":\"\",\"gender\":2,\"avatar_m\":\"http://img.558idc.com/uploadfile/allimg/java/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.m\",\"cover\":\"http://img.558idc.com/uploadfile/allimg/java/default_user_cover_10.jpg-usercover.display\",\"custom_url\":\"\",\"experience\":{\"value\":59,\"level_info\":{\"name\":\"\",\"value\":1}},\"id\":2384288641,\"birthday\":\"\",\"country_num\":null,\"avatar_s\":\"http://img.558idc.com/uploadfile/allimg/java/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.s\",\"country_code\":null,\"email_verified\":false,\"is_hunter\":false,\"cdc2\":false,\"avatar_l\":\"http://img.558idc.com/uploadfile/allimg/java/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.l\",\"email\":\"\",\"user_desc\":\"\",\"points\":2},\"spot_id\":2387842143,\"is_author\":false,\"cover_image_w640\":\"http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/1/w/640/h/480/q/85\",\"region\":{\"primary\":\"\",\"secondary\":\"\"},\"comments_count\":2,\"cover_image\":\"http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/960/q/85\",\"cover_image_width\":1088,\"recommendations_count\":21}],\"desc\":\"\"}"

2、maven依赖

https://github.com/wnameless/json-flattener

 <dependency>
     <groupId>com.github.wnameless.json</groupId>
     <artifactId>json-flattener</artifactId>
     <version>0.8.1</version>
 </dependency>

3、扁平化

    /**
     * json 扁平化
     */
    public static void jsonFlatten(String jsonStr) {
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        Map<String, Object> flatMap = JsonFlattener.flattenAsMap(jsonObj.toString());
        for (Map.Entry<String, Object> entry : flatMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

备注:扁平化级别默认.隔开,若指定级别分割任意符号:

 new JsonFlattener(jsonObj.toString()).withSeparator(',').flattenAsMap();

输出结果:

data[0].center_point: {}
data[0].comments_count: 2
data[0].cover_image: http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/960/q/85
data[0].cover_image_1600: http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/1384/h/1384/q/85
data[0].cover_image_height: 816
data[0].cover_image_s: http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/1/w/280/h/280/q/75
data[0].cover_image_w640: http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/1/w/640/h/480/q/85
data[0].cover_image_width: 1088
data[0].date_tour: 2016-06-19T01:19:07+08:00
data[0].index_cover: http://img.558idc.com/uploadfile/allimg/java/photo_d_2016_06_19_01_21_20_989_123986672_17737936936133063098.jpg?imageView/2/w/960/q/85
data[0].index_title: 
data[0].is_author: false
data[0].is_hiding_location: false
data[0].is_liked: false
data[0].location_alias: 
data[0].poi: 
data[0].recommendations_count: 21
data[0].region.primary: 
data[0].region.secondary: 
data[0].share_url: btrip/spot/2387842143/
data[0].spot_id: 2387842143
data[0].text: 献给爱我们的女神
data[0].timezone: Asia/Shanghai
data[0].trip_id: 2387282916
data[0].user.avatar_l: http://img.558idc.com/uploadfile/allimg/java/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.l
data[0].user.avatar_m: http://img.558idc.com/uploadfile/allimg/java/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.m
data[0].user.avatar_s: http://img.558idc.com/uploadfile/allimg/java/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.s
data[0].user.birthday: 
data[0].user.cdc2: false
data[0].user.cover: http://img.558idc.com/uploadfile/allimg/java/default_user_cover_10.jpg-usercover.display
data[0].user.custom_url: 
data[0].user.email: 
data[0].user.email_verified: false
data[0].user.experience.level_info.name: 
data[0].user.experience.level_info.value: 1
data[0].user.experience.value: 59
data[0].user.gender: 2
data[0].user.id: 2384288641
data[0].user.is_hunter: false
data[0].user.location_name: 
data[0].user.mobile: 
data[0].user.name: 丑到没墙角
data[0].user.points: 2
data[0].user.resident_city_id: 
data[0].user.user_desc: 
data[0].view_count: 36207
desc: 
type: 10

4、去扁平化

String unflattenJson = JsonUnflattener.unflatten(flattenJson);

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。

网友评论