0

Json 只有整数和字符串。我有一个“列表”,里面的“地图”,我没有附加数据,因为它们可以是任何数据。问题是我在这个“字符串”类型的“列表”中有一个日期,如何更改为“日期”类型?在代码list.each和map.each中,某个步骤的值将是String类型的日期值,我可以使用正则表达式检查日期,但是如何将其更改为Date?地图.put?

def list = jsonSlurper.parseText JSON
 def typeMap = [:].withDefault { key -> "String" }
            list.each { map ->
                map.each { key, values ->
                    if (values != null) {
                        typeMap[key] = getTypeDef(values)
                        println('value ' + values + ' typeMap ' + typeMap[key])
                        //typeMap[key] = values.getClass().simpleName
                    }
                }
            }

用于测试该值的正则表达式将被日期掩盖以更改类型。

if (values ==~ /^(0?[1-9]|[12][0-9]|3[01])[\\/\-.](0?[1-9]|1[012])[\\/\-.]\d{4}\s[0-2]?[0-9]:[0-5][0-9]:[0-5][0-9]\u0024/){}
4

1 回答 1

0

不是最佳的,但对于小型 json 应该可以工作

import groovy.json.*

def JSON='''
{"a":[{"d1":"2021-02-25 18:56:13","s":"s123","i":456}]}
'''

def detectDates(Object o){
    if(o instanceof List)return o.collect{ detectDates(it) }
    if(o instanceof Map)return o.collectEntries{k,v-> [k,detectDates(v)] }
    if(o instanceof String && o==~/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)return Date.parse('yyyy-MM-dd HH:mm:ss',o)
    return o
}

def o = new JsonSlurper().parseText(JSON)

assert o.a[0].d1 instanceof String
o = detectDates(o)
assert o.a[0].d1 instanceof Date
println new JsonBuilder(o).toPrettyString()


于 2021-05-13T00:15:03.313 回答