RestAssured JsonPath: How to filter json objects from json

3.5k views Asked by At

I'm trying to take an array of objects from json file and i have an issue.

path.get("wgcTournaments.items")

What path i should use to get all items(item0, item1, item2 ...) in items?

Can you please give me an advice how to do it.

Json example

{
  "wgcTournaments": {
    "items": {
      "jcr:primaryType": "nt:unstructured",
      "item0": {
        "jcr:primaryType": "nt:unstructured",
        "test": "test",
        "test1": "test1"
      },
      "item1": {
        "jcr:primaryType": "nt:unstructured",
        "test": "test",
        "test1": "test1"
      },
      "item2": {
        "jcr:primaryType": "nt:unstructured",
        "test": "test",
        "test1": "test1"
      },
      "item3": {
        "jcr:primaryType": "nt:unstructured",
        "test": "test",
        "test1": "test1"
      }
    }
  }
}

The best way to filter item from items object but i don't understand how to do it with json path.

2

There are 2 answers

0
Roman On BEST ANSWER

Finally i found a solution for my question.

If you want to get item from items you need to use this one json Path

path.getObject("wgcTournaments.items*.
find{it.key.startsWith('item')}.value",ItemClass[].class);

Note: it was RestAssured and he uses Gpath more details you can find here http://docs.groovy-lang.org/latest/html/documentation/#_gpath

4
AntoineB On

You are trying to deserialize an object into an array of objects. Either your code or your JSON (most likely) is wrong.

If you want to deserialize items as an array, your JSON should be the following:

{
  "wgcTournaments": {
    "items": [
        {
          "jcr:primaryType": "nt:unstructured",
          "item0": {},
          "item1": {},
          "item2": {},
          "item3": {}
        }
    ]
  }
}

Otherwise, if your JSON is correct, you should deserialize your JSON using the following line:

path.getObject("wgcTournaments.items", MyClass.class)

EDIT: After your edit, this seems to be what you want:

If your JSON in correct and you indeed want an array, I assume that each itemX is a the key and {} the corresponding value. In this case, you have to know that you cannot have an associative array in JSON, you should use a custom solution to deserialize it, because your associative array will be converted into an object.