Reputation: 1310
Spring supports @JsonView
since version 4.1.
Annotating a Spring contoller's (annotated with @RestController
) method with @JsonView
that has multiple identifiers I got the following exception:
java.lang.IllegalArgumentException: @JsonView only supported for request body advice with exactly 1 class argument: org.springframework.web.method.HandlerMethod$HandlerMethodParameter@a566e37e
Apparently according to the JsonViewResponseBodyAdvice
's Javadoc the following is true:
Note that despite @JsonView allowing for more than one class to be specified, the use for a response body advice is only supported with exactly one class argument. Consider the use of a composite interface.
Likewise when annotating a controller's method argument (annotated with @RequestBody
) also with @JsonView
that has multiple identifiers; according to the JsonViewRequestBodyAdvice
's Javadoc:
Note that despite @JsonView allowing for more than one class to be specified, the use for a request body advice is only supported with exactly one class argument. Consider the use of a composite interface.
Does anybody knows if a fix is planned? My current Spring version is 4.2.4.
This would be extremely useful creating json views for public, private (extending public), summary and detailed (extending summary) views and then combining them in the controller methods!
Upvotes: 19
Views: 11430
Reputation: 6209
As explained in Jackson JsonView documentation, "only single active view per serialization; but due to inheritance of Views, can combine Views via aggregation".
Concretely, if you want to use both Foo
and Bar
JsonViews, define a FooBar
interface that combine them as following:
interface Foo {}
interface Bar {}
interface FooBar extends Foo, Bar {}
You can then annotate your fields with @JsonView(Foo.class)
or @JsonView(Bar.class)
and use @JsonView(FooBar.class)
at controller level.
Upvotes: 27