Using Grails and the scenario is if I have an object passed in from an HTTP request and I iterate through the object and grab all possible objects as in:
if (params.colors) {
for (String color in params.colors) {
println color
}
}
If a [Ljava.lang.String is passed in (i.e., params.colors = ["blue","green","yellow"]) then your output is as expected:
blue
green
yellow
But if params.colors = "blue", then of course, groovy will tokenize "blue" and you'll get the output:
b
l
u
e
I suppose I should be checking to see if it's already an array. Unless I'm approaching this wrong or there is a groovy way of doing it.
You can access the colors param as a list using the list
method on the params
object:
for (String color in params.list('colors')) {
println color
}
This way, it won't matter if you action is called like /your_action?colors=red
or /your_action?colors=red&colors=green
or even with no colors param at all (that's why i left out the if
), params.list('colors')
will always return a list :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With