I have 2 questions:
1. Can I create one class, annotate it with JAXB annotations(for XML support) and declare in web.xml
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
for JSON (Jackson library) support? Or I need to create separately two classes for JSON and XML?
Or may be exist some more elegant way to cause REST service to return both JSON and XML?
2. How I can programmatically choose what type to return (JSON or XML)?
Thanks.
If your client wants to use a part of the URL to configure the response type, you can use a Servlet filter.
An easy way to implement overriding the representation (media type) could use a URL query parameter:
/resources/todo?format=json
The Servlet filter parses the URL query parameters, and if a format=json is present, replaces or adds the accept header "application/json".
No need for seperate classes, what you need is seperate methods:
Then in the client side, when you request for the service, you indicate in what format you want it:
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
You can always use an
Application
class to specify aMessageBodyReader
/MessageBodyWriter
for the JSON binding. I believe Jackson provides an implementation in its jar. Below is an example of anApplication
class that specifies MOXy as the JSON provider:EclipseLink JAXB (MOXy) offers native XML binding and is designed to enable you to use the same object model for both JSON and XML. You can integrate it into your JAX-RS application using the
MOXyJsonProvider
class:Server Side
You can specify that your service offers both XML and JSON messages using the
@Produces
annotation.For More Information
Client Side
You can use the MediaType to indicate the type of message. Below is an example using Jersey client APIs. Note how the URL is the same, just the requested media type is different.
For More Information