Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over an Groovy object that may be a String or a String Array

Tags:

grails

groovy

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.

like image 287
Johnnie Avatar asked Dec 27 '22 11:12

Johnnie


1 Answers

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 :)

like image 194
epidemian Avatar answered May 11 '23 09:05

epidemian