In my json there is a field with the value "01.05.2021 00:00:00", I need the type to be defined as Date, but it is defined as "String" because of the quotes, apparently. How do I make sure the type is "Date" and not String? I can change String to Date, but how can I do it in the list obtained from JSON?
Example as now: value 01.05.2021 00:00:00 typeMap String value 6 typeMap Integer
def getTypeDef(def value) {
(value instanceof BigDecimal) ? "Double" : value.getClass().simpleName
}
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
}
}
}
def types = names.collect { name -> typeMap[name] }
I can do it like this, but the problem is that the value will still be a string, not a date, but I will get Date in println.
def getTypeDef(def value) {
if (value ==~ /^(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/){
(value instanceof String) ? "Date" : value.getClass().simpleName
}
else{
(value instanceof BigDecimal) ? "Double" : value.getClass().simpleName
}
}
Here is a method to convert a String being in a "2020.04.19 12:10:36" format to Date type.
Input:
Output:
Code: