Search code examples
javaautomationrest-assured

Why can't I serialize a GET request from JSON to JAVA in Rest-assured test


i have JSON :

[
  {
    "id": "string",
    "name": "string",
    "port": 0,
    "location": "string",
    "useCustomLocation": true,
    "inMemoryMode": true,
    "enabled": true,
    "active": true,
    "autoStartup": true,
    "partitions": [
      {
        "id": "string",
        "name": "string",
        "factorUser": {
          "username": "string",
          "password": "string",
          "admin": true,
          "perms": "string"
        },
        "users": [
          {
            "username": "string",
            "password": "string",
            "admin": true,
            "perms": "string"
          }
        ]
      }
    ]
  }
]

i converted JSON to POJO with jsonformatterservice. And i received 3 classes:

public class Partition {
    private String id;
    private String name;
    private User factorUser;
    private User[] users;
...


public class User {
    private String username;
    private String password;
    private boolean admin;
    private String perms;
...

public class Root {
    private String id;
    private String name;
    private long port;
    private String location;
    private boolean useCustomLocation;
    private boolean inMemoryMode;
    private boolean enabled;
    private boolean active;
    private boolean autoStartup;
    private Partition[] partitions;
...

all these classes have Getters and Setter.

My test:

@Test
public void baseData() {
    given()
            .contentType(ContentType.JSON)
            .log().all()
            .auth()
            .preemptive()
            .basic("login", "password")
            .get(BaseUrl + STORE_INSTANCE)
            .then()
            .statusCode(200)
            .extract().as(Root.class);
}

I get exception: Cannot deserialize instance of Api.BaseData.User out of START_ARRAY token

What am I doing wrong ? I'm trying to figure it out but I can't figure out how to work with complex JSON


Solution

  • Your response is an array, it should be deserialized to array of Root class. Simple code would be:

    Root root = given()....extract().as(Root[].class)[0];
    

    or

    Root root = given()....extract().jsonPath().getList("", Root.class).get(0);