In a Spring Boot @RestController
, a response of List<T>
is serialized differently from a response of org.springframework.data.web.PagedModel<T>
, which I find unexpected. The source of the difference appears to involve this line https://github.com/spring-projects/spring-framework/blob/5c6622fd77d07ac2551a6182349df878f69b17b1/spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java#L468
A type of List<T>
is classified by getJavaType
as a CollectionType
while a type of PagedModel<T>
is classified as a SimpleType
.
The immediate consequence is to affect this line https://github.com/spring-projects/spring-framework/blob/5c6622fd77d07ac2551a6182349df878f69b17b1/spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java#L476
For objects of type List<T>
, javaType.isContainerType()
evaluates to true but not for PagedModel<T>
. So, in the next line, List<T>
receives a customised objectWriter
but PagedModel<T>
does not.
if (javaType != null && (javaType.isContainerType() || javaType.isTypeOrSubTypeOf(Optional.class))) {
objectWriter = objectWriter.forType(javaType);
}
One consequence of this is that if you have a REST endpoints for /widgets
that returns PagedModel<T>
and another for /widgets/{id}
that returns a single object of type T
, the entities in PagedModel<T>
may be serialized differently than the single object - if you have defined polymorphic serialization for objects of type T
, it will be applied for single entity responses but not for PagedModel<T>
responses. A further immediate consequence is that there is no straightforward way to use polymorphic serialization with PagedModel
responses.