java如何實(shí)現(xiàn)嵌套對象轉(zhuǎn)大map(扁平化)
嵌套對象轉(zhuǎn)大map(扁平化)
部分業(yè)務(wù)場景在傳輸數(shù)據(jù)時(shí),需要的數(shù)據(jù)格式是扁平化的json格式,而在java對象中有時(shí)候?yàn)榱私怦顣?huì)做一些嵌套(即對象中包含對象,多層也是常有)。
下面的代碼可以提供該能力
- 處理單個(gè)對象: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轉(zhuǎn)為map * * @date 2022-05-30 10:50 */ @Slf4j public class ObjectToMapUtil { private static final String SEPARATOR = "_"; /** * 嵌套對象轉(zhuǎn)大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嵌套對象轉(zhuǎn)大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上發(fā)現(xiàn)了一個(gè)比較好的JSON扁平化和去扁平化處理方法,話不多說,直接開干。
1、扁平化數(shù)據(jù)(網(wǎng)上找的一json大串)
"{\"type\":10,\"data\":[{\"text\":\"獻(xiàn)給愛我們的女神\",\"is_liked\":false,\"index_cover\":\"http://photos.breadtrip.com/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://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/1384/h/1384/q/85\",\"cover_image_s\":\"http://photos.breadtrip.com/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\":\"丑到?jīng)]墻角\",\"resident_city_id\":\"\",\"mobile\":\"\",\"gender\":2,\"avatar_m\":\"http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.m\",\"cover\":\"http://photos.breadtrip.com/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://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.s\",\"country_code\":null,\"email_verified\":false,\"is_hunter\":false,\"cdc2\":false,\"avatar_l\":\"http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.l\",\"email\":\"\",\"user_desc\":\"\",\"points\":2},\"spot_id\":2387842143,\"is_author\":false,\"cover_image_w640\":\"http://photos.breadtrip.com/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://photos.breadtrip.com/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()); ? ? ? ? } ? ? }
備注:扁平化級別默認(rèn).隔開,若指定級別分割任意符號:
?new JsonFlattener(jsonObj.toString()).withSeparator(',').flattenAsMap();
輸出結(jié)果:
data[0].center_point: {}
data[0].comments_count: 2
data[0].cover_image: http://photos.breadtrip.com/photo_d_2016_06_19_01_21_20_926_123986672_17737936923172662193.jpg?imageView/2/w/960/q/85
data[0].cover_image_1600: http://photos.breadtrip.com/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://photos.breadtrip.com/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://photos.breadtrip.com/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://photos.breadtrip.com/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: 獻(xiàn)給愛我們的女神
data[0].timezone: Asia/Shanghai
data[0].trip_id: 2387282916
data[0].user.avatar_l: http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.l
data[0].user.avatar_m: http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.m
data[0].user.avatar_s: http://photos.breadtrip.com/avatar_41_b8_aedfd71640e3ec09d0c30edc47df04dc56dbf38a.jpg-avatar.s
data[0].user.birthday:
data[0].user.cdc2: false
data[0].user.cover: http://photos.breadtrip.com/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: 丑到?jīng)]墻角
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);
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
如何用Java?幾分鐘處理完?30?億個(gè)數(shù)據(jù)(項(xiàng)目難題)
現(xiàn)有一個(gè) 10G 文件的數(shù)據(jù),里面包含了 18-70 之間的整數(shù),分別表示 18-70 歲的人群數(shù)量統(tǒng)計(jì),今天小編通過本文給大家講解如何用Java?幾分鐘處理完?30?億個(gè)數(shù)據(jù),這個(gè)問題一直以來是項(xiàng)目難題,今天通過本文給大家詳細(xì)介紹下,感興趣的朋友一起看看吧2022-07-07SpringBoot動(dòng)態(tài)定時(shí)功能實(shí)現(xiàn)方案詳解
在SpringBoot項(xiàng)目中簡單使用定時(shí)任務(wù),不過由于要借助cron表達(dá)式且都提前定義好放在配置文件里,不能在項(xiàng)目運(yùn)行中動(dòng)態(tài)修改任務(wù)執(zhí)行時(shí)間,實(shí)在不太靈活。現(xiàn)在我們就來實(shí)現(xiàn)可以動(dòng)態(tài)修改cron表達(dá)式的定時(shí)任務(wù),感興趣的可以了解一下2022-11-11使用Hibernate根據(jù)實(shí)體類自動(dòng)生成表的方法
這篇文章主要介紹了使用Hibernate根據(jù)實(shí)體類自動(dòng)生成表的方法,該篇提供了兩種方法,可以根據(jù)需要選擇其一,希望對你有所幫助,如有不對的地方還望指正2023-03-03Java垃圾回收機(jī)制的finalize方法實(shí)例分析
這篇文章主要介紹了Java垃圾回收機(jī)制的finalize方法,結(jié)合實(shí)例形式分析了finalize方法的特點(diǎn)及在垃圾回收機(jī)制中的相關(guān)操作技巧,需要的朋友可以參考下2019-08-08SpringBoot實(shí)現(xiàn)License生成和校驗(yàn)的過程詳解
在我們向客戶銷售商業(yè)軟件的時(shí)候,常常需要對所發(fā)布的軟件實(shí)行一系列管控措施,諸如驗(yàn)證使用者身份、軟件是否到期,以及保存版權(quán)信息和開發(fā)商詳情等,所以本文給大家介紹了SpringBoot實(shí)現(xiàn)License生成和校驗(yàn)的過程,需要的朋友可以參考下2024-09-09