{title:'Per-media-type Swaps', updated:'8.1.0,8.2.0'}

Swaps can also be defined per-media-type.

The {@link oaj.swap.ObjectSwap#forMediaTypes()} method can be overridden to provide a set of media types that the swap is invoked on. It's also possible to define multiple swaps against the same object as long as they're differentiated by media type. When multiple swaps are defined, the best-match media type is used.

In the following example, we define 3 swaps against the same object. One for JSON, one for XML, and one for all other types.

| public class ObjectSwapTest { | | public static class MyPojo {} | | public static class MyJsonSwap extends StringSwap<MyPojo> { | @Override /* ObjectSwap */ | public MediaType[] forMediaTypes() { | return MediaType. forStrings("*/json"); | } | @Override /* ObjectSwap */ | public String swap(BeanSession session, MyPojo pojo) throws Exception { | return "It's JSON!"; | } | } | | public static class MyXmlSwap extends StringSwap<MyPojo> { | @Override /* ObjectSwap */ | public MediaType[] forMediaTypes() { | return MediaType. forStrings("*/xml"); | } | @Override /* ObjectSwap */ | public String swap(BeanSession session, MyPojo pojo) throws Exception { | return "It's XML!"; | } | } | | public static class MyOtherSwap extends StringSwap<MyPojo> { | @Override /* ObjectSwap */ | public MediaType[] forMediaTypes() { | return MediaType. forStrings("*/*"); | } | @Override /* ObjectSwap */ | public String swap(BeanSession session, MyPojo pojo) throws Exception { | return "It's something else!"; | } | } | | @Test | public void doTest() throws Exception { | | SerializerSet serializers = SerializersSet. create() | .add(JsonSerializer. class, XmlSerializer. class, HtmlSerializer. class) | .forEach(x -> x.swaps(MyJsonSwap. class, MyXmlSwap. class, MyOtherSwap. class)) | .forEachWS(x -> x.ws()) | .build(); | | MyPojo myPojo = new MyPojo(); | | String json = seralizers.getWriterSerializer("text/json").serialize(myPojo); | assertEquals("'It\\'s JSON!'", json); | | String xml = seralizers.getWriterSerializer("text/xml").serialize(myPojo); | assertEquals("<string>It's XML!</string>", xml); | | String html = seralizers.getWriterSerializer("text/html").serialize(myPojo); | assertEquals("<string>It's something else!</string>", html); | } | }

When multiple swaps match the same media type, a best-match algorithm is applied to find the correct swap to use.

In later sections we describe how annotations can be used to shorten this syntax:

| @Swap(MyJsonSwap. class) | @Swap(MyXmlSwap. class) | @Swap(MyOtherSwap. class) | public static class MyPojo {} | | @Swap(mediaTypes="*/json") | public static class MyJsonSwap extends ObjectSwap<MyPojo,String> {...} | | @Swap(mediaTypes="*/xml") | public static class MyXmlSwap extends ObjectSwap<MyPojo,String> {...} | | @Swap(mediaTypes="*/*") | public static class MyOtherSwap extends ObjectSwap<MyPojo,String> {...}