Home > Mobile >  returning a sub list from a json list in groovy active choices reactive reference parameter
returning a sub list from a json list in groovy active choices reactive reference parameter

Time:03-23

My active choices reactive reference parameter reads the following JSON file

{
"Name": "Tom",
"Age": "25",
"Subjects": ["English", "Physics", "Chemistry", "Biology", "Maths"]
}

The referenced parameters are file, Nos (previous active choices reactive parameter) which is a radio button with values 1, 2, 3, 4, 5

Now based on the values of Nos, I have to display the subjects. This is what I do:

import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(file))
return config.Subjects

With the above code, the output is,

 1. English
 2. Physics
 3. Chemistry
 4. Biology
 5. Maths

If I try to return config.Subjects.take(Nos) or config.Subjects.subList(Nos), which I expect, if Nos = 3 to be

1. English
2. Physics
3. Chemistry

But I see nothing. Then I tried,

import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(file))
list = []
i = 0
config.Subjects.each {
while (i < Nos){
list.add "$it".toString()
i = i   1
}
}
return list

But this time, I see 1. English always, no matter which radio button I select. Where am I going wrong?

CodePudding user response:

You code is almost right. You should use take to slice the list. For example take(2) will return the first two elements. So instead of returning config.Subjects, try returning (config.Subjects).take(Nos)

import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(file))
return (config.Subjects).take(Nos)

If Nos is a string, convert it into integer and return like this

import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def config = jsonSlurper.parse(new File(file))
return (config.Subjects).take(Nos.toInteger())
  • Related