Skip to content

Commit ae43b17

Browse files
committed
JsonViewResponseBodyAdvice throws IllegalArgumentException in case of >1 view class specified
Issue: SPR-12270
1 parent 7f43f02 commit ae43b17

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/JsonViewResponseBodyAdvice.java

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,27 @@
1717
package org.springframework.web.servlet.mvc.method.annotation;
1818

1919
import com.fasterxml.jackson.annotation.JsonView;
20+
2021
import org.springframework.core.MethodParameter;
2122
import org.springframework.http.MediaType;
2223
import org.springframework.http.converter.HttpMessageConverter;
2324
import org.springframework.http.converter.json.MappingJacksonValue;
2425
import org.springframework.http.server.ServerHttpRequest;
2526
import org.springframework.http.server.ServerHttpResponse;
26-
import org.springframework.util.Assert;
2727

2828
/**
2929
* A {@code ResponseBodyAdvice} implementation that adds support for
3030
* Jackson's {@code @JsonView} annotation declared on a Spring MVC
31-
* {@code @RequestMapping} or {@code @ExceptionHandler} method. The serialization
32-
* view specified in the annotation will be passed in to the
33-
* {@code MappingJackson2HttpMessageConverter} which will then use it to
31+
* {@code @RequestMapping} or {@code @ExceptionHandler} method.
32+
*
33+
* <p>The serialization view specified in the annotation will be passed in to
34+
* the {@code MappingJackson2HttpMessageConverter} which will then use it to
3435
* serialize the response body with.
3536
*
37+
* <p>Note that despite {@code @JsonView} allowing for more than one class to
38+
* be specified, the use for a response body advice is only supported with
39+
* exactly one class argument. Consider the use of a composite interface.
40+
*
3641
* @author Rossen Stoyanchev
3742
* @since 4.1
3843
* @see com.fasterxml.jackson.databind.ObjectMapper#writerWithView(Class)
@@ -49,8 +54,12 @@ protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaT
4954
MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
5055

5156
JsonView annotation = returnType.getMethodAnnotation(JsonView.class);
52-
Assert.isTrue(annotation.value().length != 0, "No view class in JsonView annotation on " + returnType);
53-
bodyContainer.setSerializationView(annotation.value()[0]);
57+
Class<?>[] classes = annotation.value();
58+
if (classes.length != 1) {
59+
throw new IllegalArgumentException(
60+
"@JsonView only supported for response body advice with exactly 1 class argument: " + returnType);
61+
}
62+
bodyContainer.setSerializationView(classes[0]);
5463
}
5564

5665
}

0 commit comments

Comments
 (0)