As suggested by @CodeChimp, the different request content types can be used to switch between different representations of the same resource. It corresponds the REST philosophy and is directly supported by Spring
as it relies on the content type to pick a serializer.
So, all I need to do is to register two serializers for class Foo
each bound to a different content type.
E.g. application/json-vnd.myCompany.com+type1
representation would be produced by Serializer1
and application/json-vnd.myCompany.com+type2
by Serializer2
accordingly. It will be up to the client then which representation to choose.
Spring MVC: Applying different JSON serializer for different annotated controller method
-
31-05-2022 - |
質問
I'm creating a REST service using annotated controllers and the content negotiation (@ResponceBody). I have two different controller methods returning instance of {{Foo}} that serves different use cases and I want the JSON representation of the {{Foo}} to be different for those methods.
For example:
@ResponseBody
public Foo method1() {... return new Foo(123); } // should produce '123'
@ResponseBody
public Foo method2() {... return new Foo(123); } // should produce '{name:"Foo", number:123}'
Of course I could use DTO pattern and return different DTOs in different methods (e.g. {{FooDTO1}} and {{FooDTO2}} respectively) and simply register different JSON serializers for those DTOs. But I wonder if there is a better way, as to me it just feels wrong to define two additional DTO classes and create disposable instances of those classes only in order to apply proper JSON serializers. Can't I just somehow hint to Spring or Jackson which Serializer should be used for which case?
解決
他のヒント
want the JSON representation of the {{Foo}} to be different for those methods
Well you'll definitely need different serializers and foos. There is no getting away from the fact. And its preferable imho.