Skip to content

Commit 3bff7bd

Browse files
committed
Serialize with type only with jackson 2.6+
Previous Jackson versions do not serialize polymorphic collections correctly when the type is specified. Issue: SPR-12811
1 parent b542b52 commit 3bff7bd

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import com.fasterxml.jackson.core.JsonEncoding;
2525
import com.fasterxml.jackson.core.JsonGenerator;
2626
import com.fasterxml.jackson.core.JsonProcessingException;
27+
import com.fasterxml.jackson.core.PrettyPrinter;
2728
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
2829
import com.fasterxml.jackson.databind.JavaType;
2930
import 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

Comments
 (0)