Newsletter

RESTful Web Service (JAX-RS) JSON Example Using Jersey

Web Services » on Jul 19, 2014 { 18 Comments } By Sivateja

This article describes how to get a JSON response from the RESTful web services using jersey implementation.  Jersey will use Jackson to convert Java objects to/form JSON, but just don’t ask me what is Jackson 🙂 ,as of now just remember its a high performance JSON processor, Jersey will use this API to the marshaling [converting the objects] process. Check this link if you would like to know more about Jackson.

These steps are mandatory in order to make Jersey to support with JSON mappings.

  • Apart from existing dependencies, add ‘jersey-json.jar‘ to your Maven pom.xml which includes all Jackson and other JSON supporting libraries
     <dependency>
                    <groupId>com.sun.jersey</groupId>
                    <artifactId>jersey-json</artifactId>
                    <version>1.8</version>
     </dependency>
  • In web.xml add “com.sun.jersey.api.json.POJOMappingFeature” as “init-param”
  • In the web service class, we need to annotate the method with @Produces(MediaType.APPLICATION_JSON). By doing so we are instructiong the service method that we are expecting the JSON output, thats it jersey will take care rest of the things

Note: In previous examples i used Tomcat 6 and JDK 1.6 but for this [JAX-RS JSON Example] example i have used JDK 1.7.

Required Files

  • pom.xml
  • web.xml
  • Customer.java
  • JsonFromRestful.java

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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>JsonFromRestfulWebServices</groupId>
  <artifactId>JsonFromRestfulWebServices</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
 
    <repositories>
           <repository>
             <id>maven2-repository.java.net</id>
              <name>Java.net Repository for Maven</name>
              <url>http://download.java.net/maven/2/</url>
              <layout>default</layout>
           </repository>
    </repositories>
 
    <dependencies>
           <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.8.2</version>
                <scope>test</scope>
           </dependency>
    
           <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-server</artifactId>
                <version>1.8</version>
           </dependency>
           
           <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-json</artifactId>
                <version>1.8</version>
          </dependency>    
     </dependencies>
 
    <build>
       <finalName>JsonFromRestfulWebServices</finalName>
       <plugins>
          <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
                 <configuration>
                    <compilerVersion>1.5</compilerVersion>
                    <source>1.5</source>
                    <target>1.5</target>
                 </configuration>
           </plugin>
       </plugins>
    </build>
</project>

 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
  <display-name>JsonFromRestfulWebServices</display-name>
  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
          <param-name>com.sun.jersey.config.property.packages</param-name>
          <param-value>java4s</param-value>
        </init-param>
        <init-param>
          <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
          <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

 Customer.java

package java4s;

public class Customer {
    
    private int custNo;
    private String custName;
    private String custCountry;
    
    public int getCustNo() {
        return custNo;
    }
    public void setCustNo(int custNo) {
        this.custNo = custNo;
    }
    public String getCustName() {
        return custName;
    }
    public void setCustName(String custName) {
        this.custName = custName;
    }
    public String getCustCountry() {
        return custCountry;
    }
    public void setCustCountry(String custCountry) {
        this.custCountry = custCountry;
    }    
}

JsonFromRestful.java

package java4s;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/customers")
public class JsonFromRestful {
    
    @GET
    @Path("/{cusNo}")
    @Produces(MediaType.APPLICATION_JSON)
    public Customer produceCustomerDetailsinJSON(@PathParam("cusNo") int no) {

        /*
         * I AM PASSING CUST.NO AS AN INPUT, SO WRITE SOME BACKEND RELATED STUFF AND
         * FIND THE CUSTOMER DETAILS WITH THAT ID. AND FINALLY SET THOSE RETRIEVED VALUES TO
         * THE CUSTOMER OBJECT AND RETURN IT, HOWEVER IT WILL RETURN IN JSON FORMAT :-)
         * */
        
        Customer cust = new Customer();        
            cust .setCustNo(no);
            cust .setCustName("Java4s");
            cust .setCustCountry("India");
        return cust;
    }
}

Output

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

18 Responses to “RESTful Web Service (JAX-RS) JSON Example Using Jersey”
  1. Rammohan says:

    All the tutorials available in Java4S are very good and real kick start to learn java based technologies.

    I would request Java4S to add Soap based web services tutorials and Spring Security tutorials as well.

  2. Mohammed says:

    Tutorials are very informative and easy to understand.

    I would like to request you to give an example for consuming the JSON object as well. And how to pass the JSON object from the client side(HTML) using javascript or jQuery to web service.

  3. Nagarjuna says:

    Tutorials are easy to understand and the way you explained with examples is damn good…:)
    You did a great job thank you siva teja..

  4. Puja says:

    Can u plz show an example of a project having spring, maven with restful webservice and junit test.

  5. Kirthika says:

    I tried the example you mentioned and I am getting the error as described below :

    HTTP Status 500 – Servlet.init() for servlet jersey-serlvet threw exception

    root cause

    com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.

    I checked in google for this error and the solution which they gave was to have the init param value properly

    com.sun.jersey.config.property.packages
    java4s

    Can you please help me to overcome this error.

  6. Vijay says:

    Tutorials are very good.You did Great job.
    Thanks Siva Teja.

  7. Ankita says:

    how can i build the same example in intellij idea.. can anyone help me???

  8. VjKumar says:

    @Kirthika : Please make sure you provided package path properly.
    E.g.

    com.sun.jersey.spi.container.servlet.ServletContainer

    com.sun.jersey.config.property.packages
    com.webser

    Hope this helps !

  9. Frank says:

    Excellent tutorial! Simple and to the point. Bravo!!!

  10. lokesh says:

    Servlet jersey-serlvet is not available

  11. Ravi Singh says:

    How to use Rest api for JIRA plugin Gadget,please show one example for it.
    Thanks in advance.

  12. veera says:

    Excellent tutorial. Can you share client program for sending request to service for geting data using @GET annotation. Atleast we need to pass pojo object from client to service.

  13. sachin says:

    sir I am trying to execute this example with same url you are providing but i am getting 404 as the response

  14. lin says:

    This is an excellent tutorial and has helped alot in understanding web services. Although, i did get few errors, i did resolve it myself. Would you be able to do a tutorial for database connectivity(postgresql if possible) in restful webservices

  15. Sujith Babu says:

    Very great examples Sir(Precise & clear)……Thanks a lot Ji 🙂

  16. pawan says:

    very great job sir, really very nice, easy to understand, great help.

  17. Ali says:

    hello
    i'm getting below error
    but h'm sure about jersey-json lib added

    org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
    SEVERE: MessageBodyWriter not found for media type=application/json, type=class java4s.Customer, genericType=class java4s.Customer.

    please help me

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.