How to deserialize a rest assured response to a list of POJOs as a sub element in the JSON?

59 Views Asked by At

So I have a JSON response from RestAssured using gson that looks like this:

{
  "name": "Jack",
  "pets": [
    {
      "name": "AppleJack",
      "id": 150,
      "animal_type": "dog",
      "date_acquired": "2014-05-15"
    },
    {
      "name": "Sharkie",
      "id": 140,
      "animal_type": "fish",
      "date_acquired": "2016-03-11"
    },
    {
      "name": "Cubbie",
      "id": 130,
      "animal_type": "dog",
      "date_acquired": "2020-11-05"
    }
  ]
}

Its part of an existing project and it is from the Response class of RestAssured configured to use gson. I am doing an java 17 upgrade from java 8 and some stuff stopped working.

I have a POJO class of a Pet, but I am not sure how to deserialize the pets part into a List.

The old project had a library that contained java classes for the whole JSON structure and much more complicated than what's shown here that stopped working.

I was hoping I can extract subparts of the response, as there are a lot places where its like this. Lists of something as a sub part.

I can extract the pets using Response.path("pets") but then I get a hashmap that I am not sure how to convert to a List.

The old code used Response.as(PetOwner.class)

PetOwner.class is an old library that isn't maintained anymore and the JSON is complex.

I am pretty new to RestAssured and Java 17.

1

There are 1 best solutions below

0
Fouzan Jafri On

Create 2 class

public class Pet{
    public String name;
    public int id;
    public String animal_type;
    public String date_acquired;
}

public class MainRoot{
    public String name;
    public ArrayList<Pet> pets;
}

MainRoot main = given()....when()...then().extract().response.as(MainRoot.class);