I have json response from api with structure like this:
{
"countPerPage": 20,
"totalCount": 401,
"currentPage": 1,
"totalPage": 21,
"data": [
{
"id": 1,
"catId": 12,
"dogId": 12,
"creationDate": "2022-01-03 12:29:38",
"comment": "Some comment"
},
{
"id": 2,
"catId": 13,
"dogId": 16,
"creationDate": "2022-01-08 11:14:25",
"comment": "Some comment"
},
...
]
}
and like this
{
"countPerPage": 20,
"totalCount": 226,
"currentPage": 3,
"totalPage": 12,
"data": [
{
"id": 1,
"parentId": 12,
"firstName": "John",
"lastName": "Doe",
"creationDate": "2022-01-03 12:29:38",
"age": 25
},
{
"id": 1,
"parentId": 12,
"firstName": "Michael",
"lastName": "Finder",
"creationDate": "2022-01-08 11:14:25",
"age": 24
},
...
]
}
And other with same structure.
If I create response java classes for person like this
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class PersonResponse{
@JsonProperty("id")
private int id;
@JsonProperty("parentId")
private int parentId;
@JsonProperty("firstName")
private String firstName;
@JsonProperty("lastName")
private String lastName;
@JsonProperty("creationDate")
private String creationDate;
@JsonProperty("age")
private int age;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class PersonWithCount {
@JsonProperty("countPerPage")
private int countPerPage;
@JsonProperty("totalCount")
private int totalCount;
@JsonProperty("currentPage")
private int currentPage;
@JsonProperty("totalPage")
private int totalPage;
@JsonProperty("data")
private List<PersonResponse> data;
}
And for animal like this
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class AnimalResponse{
@JsonProperty("id")
private int id;
@JsonProperty("catId")
private int catId;
@JsonProperty("dogId")
private int dogId;
@JsonProperty("creationDate")
private String creationDate;
@JsonProperty("comment")
private String comment;
}
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class AnimalWithCount {
@JsonProperty("countPerPage")
private int countPerPage;
@JsonProperty("totalCount")
private int totalCount;
@JsonProperty("currentPage")
private int currentPage;
@JsonProperty("totalPage")
private int totalPage;
@JsonProperty("data")
private List<AnimalResponse> data;
}
All works korrect. But how can I use something universal like generics, for don't copy and paste each time class with same data, where changed only last field?
I expected something like this, but it is not working
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class DataWithCount<T> {
@JsonProperty("countPerPage")
private int countPerPage;
@JsonProperty("totalCount")
private int totalCount;
@JsonProperty("currentPage")
private int currentPage;
@JsonProperty("totalPage")
private int totalPage;
@JsonProperty("data")
private List<T> data;
}
Fill variable:
personListWithCount = ObjectMapperCreator.objectMapperCreator().readValue(personResponse.getBody().asPrettyString(), PersonListWithCount.class);
Maybe I do something wrong?