1

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.

4

1 回答 1

2

当你这样做时:

String parsed_movements = parsedJson["movements"]

您将地图粘贴到字符串中,这不是您想要的。

鉴于您问题中的 json,您可以这样做

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

获取列表[65, 1, 32]

如果您收到 NPE,我认为 json 不是您在问题中显示的内容

于 2019-02-14T09:22:00.350 回答