I have Jersey Rest Webservice with server side code as
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Employee> getEmployees()
{
return new EmployeeService().getEmployees();
}
T
I am testing the service from chrome rest client.
This works fine with
Accept: application/xml
** But when I am requesting this with code
Accept: application/json
I am getting the following exception:-
javax.servlet.ServletException:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class com.rshekhar.domain.Employee, genericType=class com.rshekhar.domain.Employee.
What is the correct way of doing this.
You can use Jersey's built-in Jackson JSON library to automatically serialize JSON from any POJO classes. You just need to add Jackson JSON library to your pom.xml:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
</dependency>
Also in order to activate the POJO mapping of Jersey, you need to add the following lines in web.xml:
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
Then if your class method EmployeeService().getEmployees()
returns a list of employees, Jersey will serialize it to something like (JSON array)
{"employees": ["name":"Adam", "name":"Robert", ....]}
Can you provide more details related to jersey setup (entity classes annotations for starters)
Do you use JAXB? Which version of Jersey?
Here is nice starting point for your goal: https://github.com/jasonray/jersey-starterkit/wiki/Serializing-a-POJO-to-xml-or-json-using-JAXB
Take a look here and try out the example. It almost exactly the same usecase you have mentioned.
multiple content types in jax-rs