JSON Response with RESTEasy

RESTEasy is JBOSS-provided implementation of Jakarta-RS/JAX-RS specification for building RESTful Web Services. Jackson is is a multi-purpose Java library for processing JSON data format. Jackson aims to be the best possible combination of fast, correct, lightweight, and ergonomic for developers.

In this post, we will learn to use Jackson with RESTEasy, to convert the API response into JSON format.

1. Maven

Include the latest version of resteasy-jackson-provider module into project dependencies.

<dependency>
  <groupId>org.jboss.resteasy</groupId>
  <artifactId>resteasy-jackson-provider</artifactId>
  <version>3.15.3.Final</version>
</dependency>

Alternatively, we can use resteasy-jettison-provider module if we want to use Jettison library which is also an excellent option.

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jettison-provider</artifactId>
    <version>3.15.3.Final</version>
    <scope>test</scope>
</dependency>

Do not forget to check for the latest versions of RESTEasy core dependencies.

<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/json”

Now use the media type “application/json” 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/json")
	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 + Jackson example

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
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.