Reputation: 601
Main question: What operators, properties, etc. can be used to determine the type of variables in Groovy?
Background:
I have an arbitrarily deeply-nested dictionary data structure. It is the result of calling request.JSON
in a Grails controller. I would first like to verify certain keys are in the dictionary, with the appropriate types. The way I would like to implement this is by creating a prototypical data structure and defining a method to compare data structures. Something like:
def prototype = [ username: "JennyJeans",
message: [ subject: "Hello World!",
body: "Will write soon."
]
]
Of course, the content of the Strings here doesn't matter. Then, in my actions, I validate like this:
if(similarDataStructure(prototype, request.JSON)) {
// XXX
} else {
// report error
}
So, what does the similarDataStructure
method do? In pseudocode:
def similarDataStructure(a, b) {
if(type(a) != type(b)) return false
if(type(a) == dictionary) {
for key in a:
if(!similarDataStructure(a[key], b[key])) return false
}
return true
}
If you can think of a better way to do deep validation, let me know.
Upvotes: 1
Views: 1370
Reputation: 3214
To obtain types, you can use a.class, b.class and compare them: if(a.class == b.class) { }
To check if it's a dictionary, you can call: a instanceof Map
.
However, try the following code in Groovy console to see it yourself ;-)
def src = [ username: "JennyJeans",
message: [ subject: "Hello World!",
body: "Will write soon."]
]
def p1 = [ username: "JennyJeans",
message: [ subject: "Hello World!",
body: "Will write soon."]
]
def p2 = [ username: "JennyJeans",
message: [ subject: "Hello World!",
body: "Will read soon."]
]
println src == p1
println src == p2
Upvotes: 1