Groovy代码优化-递归格式化参数

    xiaoxiao2021-03-25  145

    根据现在的分享活动返回的报文中带有amount以及time的数据,老大希望能将他们格式化成希望的格式,并且希望能写一个通用的服务来调取这样的功能。。。 由于报文的格式各种各样。。。such as …

    def c = [ hhh : 123123, amount: 90 ] def b = [ name : 'cqc', amount: 123213, ] Map a = [ id : 1, amount: 234, desc : 'asdasd', user : [b, c] ] Map d = [ rewardDays: 72, cashedAmount: 170.00, rewardAmounts: 200.00, billCount: null, detail: [ [ rewardDays: 2, status: 1, amount: null, time: 'FriMar0310: 23: 57CST2017', licensePlateNo: null ], [ rewardDays: null, status: 1, amount: 120.0, time: 'FriMar0310: 23: 57CST2017', licensePlateNo: null ], [ rewardDays: 30, status: 1, amount: 50.0, time: 'FriMar0310: 23: 57CST2017', ] ] ]

    以上都是比较普遍的,还有个别比较特殊的数据格式还没考虑进来。。。

    该数据格式比较适用于多叉树查找。。。递归调用。。。我用的方法比较暴力,找到这个树的根然后递归调用这个节点,当遍历叶子的时候找到包含amount或者time的叶子就将其格式化,并将其格式化后的数据添加到原来的节点里,由于该数据结构为map形式,所以将会替代原来的value值,赶脚很浪费空间。。。

    def displayDetail(User user) { List<Map> offerDetails = this.offerDetails(user) Map responseMap = this.offerGeneral(user) responseMap.put('detail', offerDetails); this.amountFormat(responseMap) } def amountFormat(resultMap) { if (!resultMap) { return } resultMap.collectEntries { if (it.key.toLowerCase().contains('amount')) { [it.key, it.value ? DoubleUtils.displayStringWithDecimal(it.value, 2) : 0.00] } else if (it.key.toLowerCase().contains('time')) { [it.key, DateUtils.getDateString(it.value, DateUtils.DATE_LONGTIME24_PATTERN2)] } else if (it.value instanceof Map) { [it.key, amountFormat(it.value)] } else if (it.value instanceof List) { [it.key, it.value.collect { ti -> [amountFormat(ti)] }.flatten()] } else { it } } }

    老大提供一个思路。。。先找叶子更改其value值,虽然刚开始我也是用这个思路,但是遍历更改value值得过程中,map会产生新的地址存放这个值,所以一时半会也不知道怎么解决这个问题,所以才换了一个思路。。。但是老大还是找到了问题的关键。。。使代码的重用度更高。。。

    def displayDetail(User user) { List<Map> offerDetails = this.offerDetails(user) Map responseMap = this.offerGeneral(user) responseMap.put('detail', offerDetails); // this.amountFormat(responseMap) eachLeaf responseMap, { entry -> if(entry.key.toLowerCase().contains('amount')) { entry.value = entry.value ? DoubleUtils.displayStringWithDecimal(entry.value, 2) : 0.00 } else if(entry.key.toLowerCase().contains('time')){ entry.value = DateUtils.getDateString(entry.value, DateUtils.DATE_SHORTDATE2_PATTERN) } } } def eachLeaf(value, entry=null, Closure runOnLeaf){ if(value instanceof Map){ value.each{ eachLeaf(it.value, it, runOnLeaf) } } else if(value instanceof List){ value.each{ eachLeaf(it, runOnLeaf) } } else { if(entry){ runOnLeaf(entry) } } }

    老大使用了闭包使整个递归的调用更加灵活!!!

    现在还有一个新的需求就是当数据结构中包含list的基础数据类型,无法处理。。。

    def a = [ amount: [1,2,3,4] ... ]

    如果有比较好的方法或者思路欢迎提供!!!

    转载请注明原文地址: https://ju.6miu.com/read-912.html

    最新回复(0)