In cases where I want to parse JSON in a domain object that I defined in order to contain a collection of enumerations, I find that Groovy is not forcibly loading the contents of the collection, which I suppose should not be expected in any case, since generics are compile time issue.
If I naively execute type coercion in the parsed JSON, my collections will contain strings at runtime, which will lead to a failure of comparisons of the elements of the collection with the enumeration, regardless of the value.
An alternative is to override the setter for the enum collection and force each element. This is illustrated in the example below.
import groovy.json.*
enum Hero {
BATMAN, ROBIN
}
class AClass {
Collection<Hero> heroes
}
class BClass {
Collection<Hero> heroes
void setHeroes(Collection heroes){
this.heroes = heroes.collect { it as Hero }
}
}
class CClass {
AClass a
BClass b
}
def json = '''
{
"a":
{
"heroes":["BATMAN", "ROBIN"]
},
"b":
{
"heroes":["BATMAN", "ROBIN"]
}
}
'''
def c = new JsonSlurper().parseText(json) as CClass
assert c.a.heroes[0].class == String
assert c.b.heroes[0].class == Hero
, , , , Groovy .