设为首页 加入收藏

TOP

做一次面向对象的体操:将JSON字符串转换为嵌套对象的一种方法(四)
2018-09-04 20:46:40 】 浏览:590
Tags:一次 面向 对象 体操 JSON 字符串 转换 方法
+ " \"item_price_change_log:id:3333\": \"3333\",\n" + " \"item_price_change_log:id:4444\": \"4444\",\n" + " \"item_price_change_log:item_id:3333\": \"9876666\",\n" + " \"item_price_change_log:item_id:4444\": \"9878888\",\n" + " \"item_price_change_log:detail:3333\": \"haha3333\",\n" + " \"item_price_change_log:detail:4444\": \"haha4444\"\n" + "}"; public static void main(String[] args) { Order order = transferOrder(json); System.out.println(JSON.toJSONString(order)); } public static Order transferOrder(String json) { return relate(underline2camelForMap(group(json))); } /** * 转换成 Map[tablename:id => Map["field": value]] */ public static Map<String, Map<String,Object>> group(String json) { Map<String, Object> map = JSON.parseObject(json); Map<String, Map<String,Object>> groupedMaps = new HashMap(); map.forEach( (keyInJson, value) -> { TableField tableField = TableField.buildFrom(keyInJson); String key = tableField.getTablename() + ":" + tableField.getId(); Map<String,Object> mapForKey = groupedMaps.getOrDefault(key, new HashMap<>()); mapForKey.put(tableField.getField(), value); groupedMaps.put(key, mapForKey); } ); return groupedMaps; } public static Map<String, Map<String,Object>> underline2camelForMap(Map<String, Map<String,Object>> underlined) { Map<String, Map<String,Object>> groupedMapsCamel = new HashMap<>(); Set<String> ignoreSets = new HashSet(); underlined.forEach( (key, mapForKey) -> { Map<String,Object> keytoCamel = TransferUtil.generalMapProcess(mapForKey, TransferUtil::underlineToCamel, ignoreSets); groupedMapsCamel.put(key, keytoCamel); } ); return groupedMapsCamel; } /** * 将分组后的子map先转成相应单个对象,再按照某个key值进行关联 */ public static Order relate(Map<String, Map<String,Object>> groupedMaps) { List<Item> items = new ArrayList<>(); List<ItemCore> itemCores = new ArrayList<>(); List<ItemPrice> itemPrices = new ArrayList<>(); List<ItemPriceChangeLog> itemPriceChangeLogs = new ArrayList<>(); groupedMaps.forEach( (key, mapForKey) -> { if (key.startsWith("item:")) { items.add(map2Bean(mapForKey, Item.class)); } else if (key.startsWith("item_core:")) { itemCores.add(map2Bean(mapForKey, ItemCore.class)); } else if (key.startsWith("item_price:")) { itemPrices.add(map2Bean(mapForKey, ItemPrice.class)); } else if (key.startsWith("item_price_change_log:")) { itemPriceChangeLogs.add(map2Bean(mapForKey, ItemPriceChangeLog.class)); } } ); Map<String ,List<Item>> itemMap = items.stream().collect(Collectors.groupingBy( Item::getItemCoreId )); Map<String ,List<ItemPrice>> itemPriceMap = itemPrices.stream().collect(Collectors.groupingBy( ItemPrice::getItemId )); Map<String ,List<ItemPriceCh
首页 上一页 1 2 3 4 5 6 下一页 尾页 4/6/6
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇SpringBoot | 第十五章:基于Post.. 下一篇Map大家族的那点事儿(2) :Abstra..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目