XML Response with RESTEasy and JAXB

RESTEasy is a JBOSS-provided implementation of Jakarta-RS/JAX-RS specification for building RESTful Web Services. JAXB is used for mapping Java classes to equivalent XML documents and vice versa. It is done using marshalling and unmarshalling features of JAXB.

This post will teach us to use JAXB with RESTEasy to convert the API response into XML format.

1. Maven

Include the latest version of resteasy-jaxb-provider module into project dependencies along with RESTEasy core dependencies.

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxb-provider</artifactId>
    <version>6.2.1.Final</version>
</dependency>

<dependency>
  <groupId>org.jboss.resteasy</groupId>
  <artifactId>resteasy-core</artifactId>
  <version>6.2.1.Final</version>
</dependency>
<dependency>
  <groupId>org.jboss.resteasy</groupId>
  <artifactId>resteasy-client</artifactId>
  <version>6.2.1.Final</version>
</dependency> 

2. Use Mediatype “application/XML”

Now use the media type “application/xml” in the @Produces annotation to add support for JSON responses.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

import com.howtodoinjava.model.User;

@Path("/user-management")
public class UserManagementModule
{
	@GET
	@Path("/users/{id}")
	@Produces("application/xml")
	public Response getUserById(@PathParam("id") Integer id)
	{
		User user = new User();
		user.setId(id);
		user.setFirstName("Lokesh");
		user.setLastName("Gupta");
		return Response.status(200).entity(user).build();
	}
}

3. Demo

When we deploy above-built application in tomcat and hit the URL: ” http://localhost:8080/RESTfulDemoApplication/user-management/users/10″, below is the response.

RESTEasy JAXB Example

Happy Learning !!

Comments

Subscribe
Notify of
guest
9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.