Reputation: 3
I'm new to Groovy but using it to extract responses from JSON response stored in a file.
Below is a snippet of the JSON:
"attachments": [
{
"type": "AttachmentText",
"text": "Line 1"
},
{
"type": "AttachmentText",
"text": "This is a different text and can be anything but always > 8 characters"
}
],
I'm trying to get the text based on the condition that the text in the first case is always < 8
characters whereas the text in the second case is always >8
characters - there is no other way to distinguish the attachment elements otherwise. However my code only gives me 1 of the responses.
{
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(jsontocsv.toString())
def array1 = object.attachments
if(array1 != null && !array1.isEmpty())
{
for(def i =0; i<object.attachments.size();i++)
{
if(object.attachments[i].type=="AttachmentText" && object.attachments[i].text.length()>8) {
varaiable1 = RString.of(object.attachments[i].text.toString())
}
else{
variable2 = RString.of("Nothing here")
}
}
}
else {
variable3 = RString.of("No attachments")
}
}
I'm expecting that my variable1
will show response This is a different text and can be anything but always > 8 characters but I keep getting Nothing here instead.
Any idea how to fix this?
Upvotes: 0
Views: 999
Reputation: 14640
Maybe something like this?
def methodReturningLongText()
{
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(jsontocsv.toString())
def variable1 = RString.of("No attachments")
def array1 = object.attachments
if(array1)
{
variable1 = RString.of("Nothing here")
for(def i =0; i<array1.size();i++)
{
if(object.attachments[i].type=="AttachmentText" && object.attachments[i].text.length()>8) {
variable1 = RString.of(object.attachments[i].text.toString());
break;
}
}
}
return variable1
}
Notes:
if (array1)
Upvotes: 1