2424import com .fasterxml .jackson .core .JsonEncoding ;
2525import com .fasterxml .jackson .core .JsonGenerator ;
2626import com .fasterxml .jackson .core .JsonProcessingException ;
27+ import com .fasterxml .jackson .core .PrettyPrinter ;
2728import com .fasterxml .jackson .core .util .DefaultPrettyPrinter ;
2829import com .fasterxml .jackson .databind .JavaType ;
2930import com .fasterxml .jackson .databind .ObjectMapper ;
@@ -65,6 +66,10 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener
6566 private static final boolean jackson23Available = ClassUtils .hasMethod (ObjectMapper .class ,
6667 "canDeserialize" , JavaType .class , AtomicReference .class );
6768
69+ // Check for Jackson 2.6+ for support of generic type aware serialization of polymorphic collections
70+ private static final boolean jackson26Available = ClassUtils .hasMethod (ObjectMapper .class ,
71+ "setDefaultPrettyPrinter" , PrettyPrinter .class );
72+
6873
6974 protected ObjectMapper objectMapper ;
7075
@@ -233,15 +238,16 @@ protected void writeInternal(Object object, Type type, HttpOutputMessage outputM
233238 FilterProvider filters = null ;
234239 Object value = object ;
235240 JavaType javaType = null ;
236- if (type != null ) {
237- javaType = getJavaType (type , null );
238- }
239241 if (object instanceof MappingJacksonValue ) {
240242 MappingJacksonValue container = (MappingJacksonValue ) object ;
241243 value = container .getValue ();
242244 serializationView = container .getSerializationView ();
243245 filters = container .getFilters ();
244246 }
247+ if (jackson26Available && type != null && value != null
248+ && TypeUtils .isAssignable (type , value .getClass ())) {
249+ javaType = getJavaType (type , null );
250+ }
245251 ObjectWriter objectWriter ;
246252 if (serializationView != null ) {
247253 objectWriter = this .objectMapper .writerWithView (serializationView );
@@ -252,7 +258,7 @@ else if (filters != null) {
252258 else {
253259 objectWriter = this .objectMapper .writer ();
254260 }
255- if (javaType != null && value != null && TypeUtils . isAssignable ( type , value . getClass ()) ) {
261+ if (javaType != null ) {
256262 objectWriter = objectWriter .withType (javaType );
257263 }
258264 objectWriter .writeValue (generator , value );
0 commit comments