How to control JSON output format from Jersey?
As you know that in XML you can represent the same
data in variety of ways by using fields, names, attributes, etc..The same is
true to JSON. In many cases different serializers produce different JSON
representation of the same objects.
JAX-RS (as well as Jersey) provide you control over
what and how you want to serialize. This is accomplished via providers.
Here is an example
of such provider (Note that the class should be marked with @Provider
annotation):
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class<?>[] types = { ListDescription.class };
public JAXBContextResolver() throws Exception {
JSONConfiguration config = JSONConfiguration.natural().build();
context = new JSONJAXBContext(config, types);
}
public JAXBContext getContext(Class<?> objectType) {
for (Class<?> type : types) {
if (type == objectType) {
return context;
}
}
return null;
}
}
Note that by creating an appropriate JSONConfiguration
(JSONConfiguration.natural().build()) you, in fact, control the output JSON
format. The JSONConfiguration class provide 4 different JSON formatters:
- natural (Jackson)
- mapped
- mappedJettison
- Badgerfish
Here is how the output will vary, depending on the choice of the
configuration. Don’t forget that the class should be annotated with A simple
class (with fields (int)ID and (String)Name) added to an ArrayList and then
returned back as a @GET return value:
@XmlRootElement
public class ListDescription{
public int ID;
public String Name;
}
@GET
@Produces({MediaType.APPLICATION_JSON })
public List<DataListInfo> getAllLists(){
List<ListDescription> lists = new ArrayList<ListDescription>();
ListDescription ls = new ListDescription();
ls.ID = 1;
ls.Name = "Test";
lists.add(ls);
return lists;
}
mappedJettison:
{"listDescriptions":{"listDescription":{"ID":1,"Name":"Test"}}}
|
mapped:
{"listDescription":{"ID":"1","Name":"Test"}}
|
natural
(jackson):
1
|
[{"ID":1,"Name":"Test"}]
|
Badgerfish:
{"listDescriptions":{"listDescription":{"ID":{"$":"1"},"Name":{"$":"Test"}}}}
|
No comments:
Post a Comment