HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / RESTEasy / RESTEasy JSON Example with Jackson

RESTEasy JSON Example with Jackson

RESTEasy is JBOSS provided implementation of JAX-RS specification for building RESTful Web Services and RESTful Java applications. Though this is not limited to be used in JBOSS only, and you can use with other servers also.

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, I am demonstrating the way to use Jackson with RESTEasy, to convert the API response in json format.

Environment used:

  1. RESTEasy 2.3.1.GA
  2. RESTEasy Jackson provider 2.3.1
  3. Tomcat 7
  4. JDK 1.6

Follow below steps to build a demo application.

1) Create a maven project and convert to eclipse web project

mvn archetype:generate -DgroupId=com.howtodoinjava -DartifactId=RESTfulDemoApplication 
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

mvn eclipse:eclipse -Dwtpversion=2.0

2) Update runtime dependencies in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.howtodoinjava</groupId>
  <artifactId>RESTfulDemoApplication</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>RESTfulDemoApplication Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <repositories>
   	<repository>
      <id>jboss</id>
      <url>http://repository.jboss.org/maven2</url>
   	</repository>
  </repositories>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- core library -->
	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		 <artifactId>resteasy-jaxrs</artifactId>
		<version>2.3.1.GA</version>
	</dependency>
	<dependency>
		<groupId>net.sf.scannotation</groupId>
		<artifactId>scannotation</artifactId>
		<version>1.0.2</version>
	</dependency>
	<!-- Jackson support -->
	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		<artifactId>resteasy-jackson-provider</artifactId>
		<version>2.3.1.GA</version>
	</dependency>	
  </dependencies>
  <build>
    <finalName>RESTfulDemoApplication</finalName>
  </build>
</project>

3) Update web.xml file for resteasy specific servlet mapping

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  	<display-name>Archetype Created Web Application</display-name>
  	<!-- Auto scan REST service -->
	<context-param>
		<param-name>resteasy.scan</param-name>
		<param-value>true</param-value>
	</context-param>
	
	<servlet>
		<servlet-name>resteasy-servlet</servlet-name>
		<servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
		</servlet-class>
	</servlet>
 
	<servlet-mapping>
		<servlet-name>resteasy-servlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>
</web-app>

4) Write a service class and model class

User.java

package com.howtodoinjava.model;
 
import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "user")
public class User implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    @XmlAttribute(name = "id")
    private int id;
 
    @XmlElement(name = "firstName")
    private String firstName;
 
    @XmlElement(name = "lastName")
    private String lastName;
 
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

UserManagementModule.java

package com.howtodoinjava.service;

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();
	}
}

5) Run the application

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
RESTEasy + Jackson example

 

Click below to download source code for this example.

 

Download Source code

 

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Prateek Ashtikar

    November 5, 2014

    Thanks. I can see User.java has warning related to JAXB. One need to add following dependency to vanish those warnings –

    javax.xml
    jaxb-api
    2.1

  2. ap

    December 30, 2013

    Hi Lokesh,

    I want to know how can we perform session management using RestEasy.
    What are the different ways in which we can do it and how they can be done.
    Please help.

    Thanks in advance.
    AP

  3. goyaldD

    November 26, 2013

    Ok. Ignore my earlier messages. I was making some mistake. Let me investigate and post what I did wrong for other’s benefit.

  4. goyaldD

    November 26, 2013

    apologies for being so dumb and copy pasting wrong error message. I was trying different URLs. I get this error with user-management in URL..

    Could not find resource for relative : /user-management/users/10 of full path: http://localhost:8080/RESTfulDemoApplication/user-management/users/10

  5. goyaldD

    November 25, 2013

    Lokesh
    First, a big thanks for sharing your experience.
    I tried your instructions and am facing some challenges. I am using eclipse Java EE IDE Indigo & Apache Tomcat/7.0.34. My RestEasy jar is at 2.3.1
    1. I created project using MVN command. While importing in eclipse, I see an error “Eclipse Maven Import error: An internal error occurred during: Importing Maven projects. Unsupported IClasspathEntry kind=4”. I could get rid of this by doing “eclipse->project->Run as->maven clean” &
    “eclipse->project->Run as->maven install”
    2. While trying to run this project on tomcat (from eclipse), I notice following error. I checked eclipse output directory and didn’t see any apps deployed under wtpwebapps folder.

    java.lang.IllegalArgumentException: Document base C:dgoyalmystuffmycodeeclipseworkspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebappsRESTfulDemoApplication does not exist or is not a readable directory
    at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:138)
    at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4906)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5086)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ….. more stack trace —

    3. Finally, I exported this project as a .war file to webapps folder. However, now I get an error
    HTTP Status 404 – Could not find resource for relative : /users/10 of full path: http://localhost:8080/RESTfulDemoApplication/users/10

    Any suggestions or ideas?

    My reference libraries are at
    jsr250-api-1.0
    activation-1.1
    junit-3.8.1
    resteasy-jaxrs-2.3.1.GA
    jaxrs-api-2.3.1.GA.jar
    commons-httpclient-3.1
    commons-logging-1.0.4
    commons-codec-1.2
    httpclient-4.1.2
    httpcore-4.1.2
    jcip-annotations-1.0
    scannotations-1.0.2
    javaassist-3.6.0.GA

    Thanks

    • Lokesh Gupta

      November 25, 2013

      Can you please follow below steps:

      https://stackoverflow.com/questions/10564684/how-to-fix-error-updating-maven-project-unsupported-iclasspathentry-kind-4

      • goyaldD

        November 26, 2013

        Thanks. As I wrote, I already resolved issue#1. I am now stuck at issue#3. I would appreciate any suggestions.

        thanks

        • Lokesh Gupta

          November 26, 2013

          You forgot “user-management” in path. Please see the image in post.

          • goyaldD

            November 26, 2013

            I am giving full path http://localhost:8080/RESTfulDemoApplication/users/10
            If there a way to configure high level DEBUG or trace logs for RESTEasy?

            Error message also shows myURL correctly.

            “Could not find resource for relative : /users/10 of full path: http://localhost:8080/RESTfulDemoApplication/users/10“

Comments are closed on this article!

Search Tutorials

RESTEasy Tutorial

  • JAX-RS – Introduction
  • RESTEasy – JBoss
  • RESTEasy – Tomcat
  • RESTEasy – @Path
  • RESTEasy – HATEOAS
  • RESTEasy – SLF4J
  • RESTEasy – Log4j
  • RESTEasy – Download
  • RESTEasy – Upload (MultipartForm)
  • RESTEasy – Upload (HTTPClient)
  • RESTEasy – Custom Validation
  • RESTEasy – Hibernate Validator
  • RESTEasy – ContainerRequestFilter
  • RESTEasy – PreProcessorInterceptor
  • RESTEasy – JAXB XML
  • RESTEasy – Jettison JSON
  • RESTEasy – Jackson JSON
  • RESTEasy – ExceptionMapper

RESTEasy Client APIs

  • RESTEasy – java.net
  • RESTEasy – JAX-RS Client
  • RESTEasy – Apache HttpClient
  • RESTEasy – JavaScript API
  • RESTEasy – ResteasyClientBuilder

RESTEasy Best Practices

  • RESTEasy – Sharing Context Data
  • RESTEasy – Exception Handling
  • RESTEasy – ETag Cache control
  • RESTEasy – GZIP Compression
  • RESTful vs. SOAP

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)