How to write a simple RESTful web service using Jersey (Part 2)?

In Part 1, we saw how to create a simple REST service that returns “Hello World!!!” as a plain text. In this part, we are going to see how to transform a Java object into XML/JSON based on user request.


  • Familiarity with the code in Part 1
  • Include the Jackson library for JSON tranformation

Step 1: Create a domain/POJO Java class named “”
Description: Please note that the POJO class is annotated with JAX-B annotation. JAX-B helps transform the Java class to XML by linking a Java type like String to XML type, in this case xsd:string.

package webservices.ch01;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "greet")
public class HelloWorld {
    private String greeting = "Hello";
    private String receiver = "World";

    public HelloWorld() {

    public HelloWorld(String greeting, String receiver) {
        this.greeting = greeting;
        this.receiver = receiver;

    public String getGreeting() { return greeting; }

    public void setGreeting(String greeting) { this.greeting = greeting; }

    public String getReceiver() { return receiver; }

    public void setReceiver(String receiver) { this.receiver = receiver; }

    public String toString() {
        return greeting + " " + receiver + "!!!";

Step 2: Add getXML() method in 
Description: Using JAXB, the HelloWorld object is transformed into an XML document. Note here the return data format is annotated as MediaType.TEXT_XML, and the method return type is JAXBElement.

public JAXBElement<HelloWorld> getXML() {
	return new JAXBElement<>(new QName("helloworldxml"), HelloWorld.class, new HelloWorld()) ;

Step 3: Add getJson() method in
Description: Using the Jackson library, a new HelloWorld is converted into a JSON string. Return data format is annotated as MediaType.APPLICATION_JSON.

public String getJson() throws JsonProcessingException {
	final HelloWorld helloWorld = new HelloWorld("Hi", "Buddy");
	return new ObjectMapper().writeValueAsString(helloWorld);

Step 4: Try the URLs now

URL: http://localhost:8080/PlayArea-1.0/helloworldapp/helloworldresources/xml

XML Output:


URL: http://localhost:8080/PlayArea-1.0/helloworldapp/helloworldresources/json

JSON Output:


(Source code for the above can be found in