Simplest working example of REST json and xml
Hello folks,
Today i will show you a complete working REST example with Glassfish V3.
I am very happy of the new java EE 6 specification that brings me to use EJB technology. Before now i never used EJB cause there was too much complexity in configuration.
Now you have to use only few annotation and let the container works for you!
We want to return complex object from the REST interface, like for example a Person:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) @XmlElement private long id; @XmlElement private String name; @XmlElement private String surname; // setters and getters omitted... } |
We used few annotation to annotate the field that will be an xml element (or a json element). That’s the only information the container needs for marshalling/unmarshalling complex object into Xml or Json.
Now we need the REST class, Â as simple as follow:
1 2 3 4 5 6 7 8 9 10 11 12 |
@Path("person") public class ExampleREST { @GET @Produces("application/xml") public Person getOne() { Person p=new Person(); p.setName("Riccardo"); p.setSurname("Casatta"); return p; } } |
We still need a boring configuration step in the web.xml, add the following:
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
We already finished our “complex” REST interface, point your browser to http://localhost:8080/projectname/person
and you get something like this:
Changing the @Produces(“application/xml”) annotation to  @Produces({“application/xml”,”application/json”}) makes the json data retrieval available, depending on the client that made the request, the container will give the appropriate response. For example making the request from javascript will return a json like this:
{“id”:”0″,”name”:”Riccardo”,”surname”:”Casatta”}
Enjoy the new Simpler way of making things in java EE 6!