When working with Spring MVC and calling a web service that returns a Page<Something>, you will encounter the error : com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of org.springframework.data.domain.PageImpl
(no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator). This tutorial will show how to fix it.
Solution
Create a Java class that extends PageImpl having a constructor annotated @JsonCreator with like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.JsonNode import org.springframework.data.domain.PageImpl import org.springframework.data.domain.PageRequest import org.springframework.data.domain.Pageable public class RestPageImpl<T> extends PageImpl<T> { @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public RestPageImpl(@JsonProperty("content") List<T> content, @JsonProperty("number") int number, @JsonProperty("size") int size, @JsonProperty("totalElements") Long totalElements, @JsonProperty("pageable") JsonNode pageable, @JsonProperty("last") boolean last, @JsonProperty("totalPages") int totalPages, @JsonProperty("sort") JsonNode sort, @JsonProperty("first") boolean first, @JsonProperty("numberOfElements") int numberOfElements) { super(content, PageRequest.of(number, size), totalElements); } public RestPageImpl(List<T> content, Pageable pageable, long total) { super(content, pageable, total); } public RestPageImpl(List<T> content) { super(content); } public RestPageImpl() { super(new ArrayList<>()); } } |
And use it like this :
1 |
Page<Clazz> page = objectMapper.readValue(results.getResponse().getContentAsString(), new TypeReference<RestPageImpl<Clazz>>() {}) |
References