JAX-RS has a bunch of built-in handlers that can marshal from several different specific Java types.
As soon as we start working with custom data binding (marshalling / unmarshalling to Java objects), we are in another ball game. Now we need another MessageBodyWriters and MesageBodyReaders .
Fortunately, there are already readers and writers for binding XML and JSON data. JAX-RS comes with standard XML marshalling / unmarshalling with one warning. We must use JAXB annotations. So, for your Test class, assuming it looks like
public class Test { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name;} public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
in order to enable the JAXB provider unmarshall / marshall, we must provide at least @XmlRootElement
@XmlRootElement public class Test { .... }
Doing this should enable XML to work.
As for JSON, JSON binding is not a standard specification parameter, but we can simply add a dependency on the project, which will automatically register the necessary provider to handle the JSON binding. You can look at pom.xml for a json-moxy example . You will see this necessary dependency.
<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-moxy</artifactId> </dependency>
The dependency that the application allows you to do is marshal / unmarshal jSON for / from our Java objects using JAXB annotations. Therefore, simply adding this dependency to pom.xml . The application should work. Just tested.
source share