1
votes

I got a JSON text which I should parse, but for some reason I can't parse it because it has another array inside. My JSON looks like that:

{
   "statementId": "1",
   "movements": [
      {
         "id": 65,
         "date": "2019-02-05",
         "number": 32,
         "balance": -4.62,
         "purpose": "1"
      },
      {
         "id": 1,
         "date": "2019-02-05",
         "number": 22,
         "balance": -3,
         "purpose": "23"
      },
      {
         "id": 32,
         "date": "2019-02-05",
         "number": 12,
         "balance": -11,
         "purpose": "2"
      }
   ],
   "startPointer": "1122",
   "endPointer": "3333"
}

I am using JsonSlurper. I want to know if it is possible to catch all the data inside "movements", I have tried to use this script:

JsonSlurper slurper = new JsonSlurper()
Map parsedJson = slurper.parseText(bodyContent)
String parsed_movements = parsedJson["movements"]

I have no problem with parsing single strings, like statementId or startPointer, but when I try to parse movements with my script it gives me result as null. I have also tried parsedJson["movements"][0] to catch first movement but it also gives me an error.

I have found a lot of things about json parsers on internet and also on stackoverflow but nothing what I seek. I really don't think that it is a duplicate question.

EDIT: I tried for statement also to put each object in array like that: def movements_array = []

for(def i = 0; i < parsedJson.movements.size(); i++) {
    movements_array << parsedJson.movements[i].id
    println(movements_array)
}

But it gives me an error: Cannot invoke method size() on null object, because parsedJson.movements is null.

1

1 Answers

2
votes

When you do:

String parsed_movements = parsedJson["movements"]

You're sticking a map into a String, which isn't what you want.

Given the json in your question, you can just do

def movementIds = new JsonSlurper().parseText(bodyContents).movements.id

To get a list of [65, 1, 32]

If you're getting NPEs I assume the json isn't what you show in the question