Prabu
Prabu

Reputation: 3728

Groovy - ArrayList remove brackets

I've parsed the Below Json file and retrieve the username value.

"LogInFunctionTest": [
    {
      "TestCaseID": "Login-TC_02",
      "TestScenario": "Negative Case - Login with unregistered username and Password",
      "TestData": [
        {
          "UserName": "usernameX",
          "Password": "passwordX"
        }
      ]

Using the below code to retrieve the UserName Value.

def InputJSON = new JsonSlurper().parse(new File(fileName))
def testDataItem = InputJSON.LogInFunctionTest.find { it.TestCaseID == Login-TC_02 }.TestData.UserName

Output - [usernameX]

After this, I want to remove the brackets from the above.

'Remove brackets from arraylist'
        testDataItem = testDataItem.substring(1, testDataItem.length() - 1)
        

I'm getting the below exception

org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.length() is applicable for argument types: () values: []
Possible solutions: last(), last(), init(), init(), get(int), get(int)

Anyone guide us on how to remove the brackets from the output?

Upvotes: 0

Views: 530

Answers (3)

Orubel
Orubel

Reputation: 324

Technically you referred to 'TestData' as a List with the brackets above so proper reference should be:

TestData[0].UserName

... or since it's all contained in the 'LogInFunctionTest' List:

LogInFunctionTest[0].TestData[0].UserName

That is if you are not going to loop/iterate through them.

Upvotes: 0

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

testDataItem = testDataItem.get(0)

might do the job.

Looks like you're reading a list of Strings, not a String.

Upvotes: 1

tim_yates
tim_yates

Reputation: 171084

testDataItem is a list of UserNames as TestData contains a list

That's why when it's displayed to you, it has [] round it...

If you just want the first one in the list, then you can do:

def testDataItem = InputJSON
    .LogInFunctionTest
    .find { it.TestCaseID == 'Login-TC_02' }
    .TestData
    .UserName
    .first()

(ie: put a call to first() at the end)

Obviously, if there's two of them, you'll only be getting the first one

You could also get the first one with .UserName[0], but .first() is more descriptive

Upvotes: 1

Related Questions