17
17
package org .springframework .web .servlet .mvc .method .annotation ;
18
18
19
19
import com .fasterxml .jackson .annotation .JsonView ;
20
+
20
21
import org .springframework .core .MethodParameter ;
21
22
import org .springframework .http .MediaType ;
22
23
import org .springframework .http .converter .HttpMessageConverter ;
23
24
import org .springframework .http .converter .json .MappingJacksonValue ;
24
25
import org .springframework .http .server .ServerHttpRequest ;
25
26
import org .springframework .http .server .ServerHttpResponse ;
26
- import org .springframework .util .Assert ;
27
27
28
28
/**
29
29
* A {@code ResponseBodyAdvice} implementation that adds support for
30
30
* 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
34
35
* serialize the response body with.
35
36
*
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
+ *
36
41
* @author Rossen Stoyanchev
37
42
* @since 4.1
38
43
* @see com.fasterxml.jackson.databind.ObjectMapper#writerWithView(Class)
@@ -49,8 +54,12 @@ protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaT
49
54
MethodParameter returnType , ServerHttpRequest request , ServerHttpResponse response ) {
50
55
51
56
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 ]);
54
63
}
55
64
56
65
}
0 commit comments