I want to provide one comprehensive REST API with support for both JSON
and XML
.
The domain model is of complex type and we note that to produce friendly JSON
and XML
on the same model using MappingJacksonHttpMessageConverter
and JaxbMarshaller
respectively tends to give either readable XML or readable JSON 1).
What's the best way to proceed?
1) Due to how objects such as maps, root tags and relations are modelled differently in json
than in xml
, the objects to serialize needs to be designed differently to get both tidy json
and tidy xml
. Utilities such as jaxb annotations only goes that far.
I can think of a few candidates
1) Create both a json and xml controller/model
public class Controller {
public Foo foo() {
return new Foo();
}
}
public class XmlController extends Controller {
@Override
public XmlFoo foo() {
return new new XmlFoo(super.foo());
}
}
public class JsonController extends Controller {
@Override
public JsonFoo foo() {
return new JsonFoo(super.foo());
}
}
Given a model object Foo
create a JsonFoo
and XmlFoo
2) Write a custom message converter
I tried this and it turned out to be a bit complicated since the view must know how to resolve e.g., a Foo
to a JsonFoo
to be able to serialize it into a readable format.
3) Let each model object serialize itself, e.g.,
public class Foo {
public String serialize(Serializer s) {
return s.serialize(this);
}
}
Based on some arbitration parameter let the controller inject the correct serializer
new Foo(new FooJsonSerializer());
new Foo(new FooXmlSerializer());