问题
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.
回答1:
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", ....]}
回答2:
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
回答3:
Take a look here and try out the example. It almost exactly the same usecase you have mentioned.
multiple content types in jax-rs
回答4:
With latest version like 1.19.1 jersey.
add following dependency
compile group: 'com.fasterxml.jackson.jaxrs', name: 'jackson-jaxrs-json-provider', version: '2.10.0.pr1'
in gradle
or if you are using maven.
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.10.0.pr1</version>
</dependency>
in maven It will work.
Thanks, Praveen R.
来源:https://stackoverflow.com/questions/20834640/how-to-send-response-as-json-in-jersey-rest