Producing and consuming JSON or XML in Java REST Services with Jersey and Jackson

This Tutorial will explain how to produce and consume JSON or XML in Java REST Services with Jersey and Jackson. Jackson is one of the best JSON Providers/parsers I have come over the so far and it's very fast. Since Jersey 2.x MOXy is the new default JSON-Binding Provider in Jersey (and therefore also in GlassFish 4). However, I have experienced that Jackson is (slightly) faster than MOXy and it is a little easier to configure. I believe that Jackson is great and that's why I write this tutorial. For demonstration of how things work we will implement two different REST Services and two simple POJOs as our "model" classes. The REST services will produce and consume JSON and the JSON serialization and de-serialization happens automatically behind the scenes - no need for any extra annotations in the "model" classes. The same thing works also for XML serialization and de-serialization. However, I have disabled that feature to show you that JSON works with simple POJOs and without any additional annotations. XML will work out of the box as soon as you add a the @XmlRootElement annotation to the model classes and enable MediaType.APPLICATION_XML for the corresponding REST services.

You can compile the Maven project and run it on any Servlet Container which supports Servlet API 3.1, i.e. Tomcat 8 or Glassfish 4. Basically, this example even runs on any Servlet API 3.0 compliant Servlet Container, i.e. Tomcat 7 oder Glassfish 3. All you would need to do is changing the web.xml slightly - that's it (see comments).

If you are interested in using Jersey with MOXy then check my other tutorial.

Table of contents:

1. Maven configuration (pom.xml)

<?xml version="1.0"?>
<project xsi:schemaLocation="" 
    xmlns="" xmlns:xsi="">
        <version.jdk>1.8</version.jdk>  <!-- 1.7 for JDK 7 -->
        <version.servlet.api>3.1.0</version.servlet.api>  <!-- use 3.0.1 for Tomcat 7 or Java EE 6 (i.e. Glassfish 3.x) -->

            <name>Maven Java Net Snapshots and Releases</name>

            <name>Maven Repository</name>

            <name>Central Repository</name>

            <name>Repository for library EclipseLink (JPA 2.0)</name>


        <!-- Jersey -->       
        <!-- do not use jettison, prefer jackson
        <!-- if you are using Jersey client specific features -->



2. Defining the web.xml

<?xml version="1.0" encoding="UTF-8"?>     
<web-app xmlns:xsi="" xmlns="" 
    id="WebApp_ID" version="3.1">

<!-- use this for Servlet API 3 (Tomcat 7, Glassfish 3.x) -->  
<web-app xmlns:xsi="" xmlns="" 
        id="WebApp_ID" version="3.0">
  <!-- we will use the Java EE 7 REST specification instead of this: -->
  <!-- <servlet> -->
    <!-- <servlet-name>JerseyServlet</servlet-name> -->
    <!--  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> -->   <!-- Glassfish 3 (Java EE 6) -->
    <!-- <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> -->                    <!-- Glassfish 4 (Java EE 7) -->
    <!-- <init-param> -->
        <!-- <param-name>jersey.config.server.provider.packages</param-name> -->
        <!-- <param-value>com.nabisoft.tutorials.tomcatjersey.service</param-value> -->
    <!-- </init-param> -->
    <!-- <load-on-startup>1</load-on-startup> -->
  <!-- </servlet> -->

3. Implementing POJOs (model classes)

We will use two very simple POJOs. Make sure to add the @XmlRootElement annotation in case you also want to consume/produce XML. You could also add some JSON annotations (but this is not required).

package com.nabisoft.tutorials.jerseyjackson.model;

import java.util.Date;

//@XmlRootElement       //only needed if we also want to generate XML
public class Message {
    private String firstName;
    private String lastName;
    private Date date;
    private String text;

    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;

    public Date getDate() {
        return date;

    public void setDate(Date date) { = date;

    public String getText() {
        return text;

    public void setText(String text) {
        this.text = text;

package com.nabisoft.tutorials.jerseyjackson.model;

import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

//@XmlRootElement       //only needed if we also want to generate XML
public class Person {
    private String firstName;
    private String lastName;
    private String dateOfBirth;
    private String[] citizenships;
    private Map<String, Object> creditCards;
    private int age;
    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;
    public String getDateOfBirth() {
        return dateOfBirth;
    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    public String[] getCitizenships() {
        return citizenships;
    public void setCitizenships(String[] citizenships) {
        this.citizenships = citizenships;
    public Map<String, Object> getCreditCards() {
        return creditCards;
    public void setCreditCards(Map<String, Object> creditCards) {
        this.creditCards = creditCards;
    public int getAge() {
        return age;
    public void setAge(int age) {
        this.age = age;

4. Implementing the REST Services

Our two REST Services are very simple as well. Make sure to add MediaType.APPLICATION_XML in case you also want to consume/produce XML.

package com.nabisoft.tutorials.jerseyjackson.jaxrs.resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.nabisoft.tutorials.jerseyjackson.model.Message;

public class MessageResource {
    public String getServerTime() {
        System.out.println("RESTful Service 'MessageService' is running ==> ping");
        return "received ping on "+new Date().toString();
    @Produces({MediaType.APPLICATION_JSON})  //add MediaType.APPLICATION_XML if you want XML as well (don't forget @XmlRootElement)
    public List<Message> getAllMessages() throws Exception{
        List<Message> messages = new ArrayList<>();
        Message m = new Message();
        m.setDate(new Date());
        m.setText("Hello World!");
        System.out.println("getAllMessages(): found "+messages.size()+" message(s) on DB");
        return messages; //do not use Response object because this causes issues when generating XML automatically
    public String postMessage(Message msg) throws Exception{
        System.out.println("First Name = "+msg.getFirstName());
        System.out.println("Last Name  = "+msg.getLastName());
        return "ok";

package com.nabisoft.tutorials.jerseyjackson.jaxrs.resource;

import java.util.HashMap;
import java.util.Map;


import com.nabisoft.tutorials.jerseyjackson.model.Person;

public class PersonResource {
    @Produces({MediaType.APPLICATION_JSON})  //add MediaType.APPLICATION_XML if you want XML as well (don't forget @XmlRootElement)
    public Person getPerson(){
        Person p = new Person();
        p.setCitizenships( new String[]{"German", "Persian"} );        
        Map<String, Object> creditCards = new HashMap<String, Object>();
        creditCards.put("MasterCard", "1234 1234 1234 1234");
        creditCards.put("Visa", "1234 1234 1234 1234");
        creditCards.put("dummy", true);
        System.out.println("REST call...");
        //return Response.ok().entity(p).build();
        return p;
    public String postPerson(Person pers) throws Exception{
        System.out.println("First Name = "+pers.getFirstName());
        System.out.println("Last Name  = "+pers.getLastName());
        return "ok";


5. Our Jackson Json Provider

Now we make sure to use Jackson.

package com.nabisoft.tutorials.jerseyjackson.jaxrs.provider;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

 * Jackson JSON processor could be controlled via providing a custom Jackson ObjectMapper instance. 
 * This could be handy if you need to redefine the default Jackson behavior and to fine-tune how 
 * your JSON data structures look like (copied from Jersey web site). * 
 * @see

public class MyJacksonJsonProvider implements ContextResolver<ObjectMapper> {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    static {
    public MyJacksonJsonProvider() {
        System.out.println("Instantiate MyJacksonJsonProvider");
    public ObjectMapper getContext(Class<?> type) {
        System.out.println("MyJacksonProvider.getContext() called with type: "+type);
        return MAPPER;

6. Our JAX-RS Application class

Now we need to wire everything together by registering the relevant classes.

package com.nabisoft.tutorials.jerseyjackson.jaxrs.application;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class ApplicationConfig extends Application {

    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        System.out.println("REST configuration starting: getClasses()");            
        //this will register Jackson JSON providers
        //we could also use this:
        //instead let's do it manually:
        //==> we could also choose packages, see below getProperties()
        System.out.println("REST configuration ended successfully.");
        return resources;
    public Set<Object> getSingletons() {
        return Collections.emptySet();
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<>();
        //in Jersey WADL generation is enabled by default, but we don't 
        //want to expose too much information about our apis.
        //therefore we want to disable wadl (http://localhost:8080/service/application.wadl should return http 404)
        //see for details
        properties.put("jersey.config.server.wadl.disableWadl", true);
        //we could also use something like this instead of adding each of our resources
        //explicitly in getClasses():
        //properties.put("jersey.config.server.provider.packages", "com.nabisoft.tutorials.mavenstruts.service");
        return properties;

7. A simple demo page (index.jsp)

The demo page offers links to directly access the services. Check your console when clicking any of the links or the buttons. The buttons demonstrate how to consume JSON in a REST Service, the links will produce JSON.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Pojo to Json Serialization using Jersey with Jackson for Java REST Services</title>
        <script src="<%=request.getContextPath() %>/js/jquery-1.11.2.min.js"></script>
            var ctxPath = "<%=request.getContextPath() %>";
                $("#postPerson, #postMessage").on("click", function(){
                        url: $(this).attr("id") === "postMessage" ? ctxPath+"/service/message/post" : ctxPath+"/service/person/post",
                        type: "POST",
                        data: '{"firstName":"Michael", "lastName":"Jordan"}',
                        contentType: "application/json",
                        cache: false,
                        dataType: "json"

       <h1>Pojo to Json Serialization using Jersey with Jackson for Java REST Services</h1>
           <li><a href="<%=request.getContextPath() %>/service/message"><%=request.getContextPath() %>/service/message</a></li>
           <li><a href="<%=request.getContextPath() %>/service/message/ping"><%=request.getContextPath() %>/service/message/ping</a></li>
           <li><a href="<%=request.getContextPath() %>/service/person/get"><%=request.getContextPath() %>/service/person/get</a></li>
           <li><button id="postPerson">Post Person</button></li>
           <li><button id="postMessage">Post Message</button></li>

8. Download Source Code

posted by test
Mon Nov 20 13:02:13 UTC 2023
posted by test
Mon May 15 09:36:58 UTC 2023
posted by zeko
Thu Mar 23 10:49:18 UTC 2023
consume rest full
test Rest
posted by Nikolaos Theocharis
Thu May 27 16:41:04 UTC 2021
I want to test Rest confume
Java Learner
posted by Ramachandra
Thu Jul 09 06:00:41 UTC 2020
Good article 
posted by Sharif Hussain Madna
Tue Apr 21 15:33:30 UTC 2020
Full Packaging 
to practice
posted by simpal kumari
Sun Jun 30 06:47:36 UTC 2019
i like this code
Jackdon Dependancies
posted by Fred
Thu Jan 10 06:20:51 UTC 2019
Thank you for this tutorial very helpful.
Do we have to add dependencies for Jackson library in our pom.xml ?
Thanks for your help.
Application -> getProperties()
posted by Haris Siddiqui
Tue Jan 08 20:39:41 UTC 2019
Can you please explain this "properties.put("jersey.config.server.provider.packages", "com.nabisoft.tutorials.mavenstruts.service");"

What is this 'com.nabisoft.tutorials.mavenstruts.service' and where is this coming from?
And why is the key = "jersey.config.server.provider.packages" ?
How to run this on intellij
posted by Sachin P L
Thu Oct 11 11:02:22 UTC 2018
Download the source code and unzip it.

Import to intelli j vie . FILE  ----> OPEN

Once imported run the following in terminal

mvn clean install -U

Once build gets successful


Click on + in left end. Choose TOMCAT from dropdown.

Choose LOCAL

Keep everything as it is.

A warning will be displayed in bottom saying" WARNING: no artifact for deployment" 

Click on fix bulb and choose your war generated by maven build.

Save and start the tomcat. The application will pop open in your browser.

XML requires no-args constructor
posted by Henno Vermeulen
Fri Aug 31 16:02:55 UTC 2018
Note that serialization to XML requires a no-args constructor to work.
posted by Jan Huba
Sun Jul 22 12:45:01 UTC 2018
i would like to test a working jackson implementation
Thank you for this tutorial
posted by Joe Tindall
Thu Jul 19 18:46:01 UTC 2018
Thank you so much for contributing this! I was pulling in a client jar needed to make outgoing rest services that was causing every response to return XML instead of JSON due to it's own @Provider for XML. I spent hours looking for how to configure the Application. You're post included everything I needed to return in JSON format. Not to mention including the import statements and code comment's made everything so much easier to understand!
posted by ayman
Sun Apr 29 14:35:53 UTC 2018
I need learn web service restful.
How to run the project?
posted by MIchal
Mon Mar 26 10:55:19 UTC 2018
When I compile the project in IntelliJ by mvn clean install and run war file from /target I get:

no main manifest attribute,

How do I fix this?
posted by Salwa Outamha
Tue Mar 28 14:02:55 UTC 2017
I would like to see if it works perfectly
What IDE to use
posted by Johnny Sundell
Sat Jan 07 19:13:01 UTC 2017
Hi, what IDE is best to use and how should I import the sample to get a runnable example
posted by Priyadharshini
Thu Jul 28 09:17:15 UTC 2016
I would like to download the sample
restfull web services
posted by vasireddy naresh
Fri Jun 10 11:13:09 UTC 2016
I want to restfull web services example sample code
jackson version
posted by ch
Sat May 07 08:56:53 UTC 2016
it that possible to specify a jackson version nr  in the pom.xml ???
RE: question about XML, answer
posted by Nabi
Tue Mar 22 09:35:54 UTC 2016
1. add xml to your service methods: @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
2. add @XmlRootElement to your entity class(es)
question about XML, answer
posted by andres
Mon Mar 21 17:51:13 UTC 2016
Hi, right now i am using this code as an example to create a restful service for json objects, but I am still needing some xml answers for other clients, but when i try to use the xml response in the services created in the example it keeps saying: "Method Not Allowed", any idea how can I fix that, maybe I am missing something in the process?

Web services using JSON
posted by Haider
Wed Jan 27 17:44:06 UTC 2016
Good reference for start working on restful web services using JSON
could not get the demo work with Tomcat 7
posted by Jim Shi
Sun Jan 17 04:48:54 UTC 2016
Even with changes suggested in web.xml, still could not get it work with tomcat 7.
Do you have a working example with Tomcat 7?
Thanks for the help with Producing and consuming JSON or XML in Java REST Servic
posted by Arthur Bezerra Nunes
Sun Jan 10 07:47:54 UTC 2016
very good article, thanks for taking my doubts and the tips. :)
Explore REST Service
posted by Radhakrishnan Rengaraj
Sat Dec 12 12:03:13 UTC 2015
Learn REST Service with good example
RE: Using your tutorial
posted by Nabi
Fri Dec 04 12:42:08 UTC 2015
Dear Bahram,
you are definitely allowed to to use any of my tutorials for your project. Adding a link to the corresponding tutorial is very welcome! Good luck with your project!
Best, Nabi
Using your tutorial
posted by Bahram Moradi
Fri Dec 04 11:23:31 UTC 2015
Hi ...
Is it allowed to use your tutorial and code in a project ( none commercial) by mentioning the url of your website as reference.
Self training.
posted by Hovhannes
Fri Nov 13 21:18:50 UTC 2015
Self training
posted by imtiyaz
Mon Oct 26 15:56:22 UTC 2015
java learning interest
posted by mtiyaz
Mon Oct 26 15:55:11 UTC 2015
very good 
Generate json
posted by swathi
Sat Sep 26 13:29:15 UTC 2015
Need the procedure to read the tag from the HTML and fetch the dynamic value that is generated from the webpage and convert to JSON form.
Webpage has table. Read the table header and fetch the data that is populated to the table.
In other words parse the HTML from browser, fetch value and convert to the JSON. Is the 1) Restful Webservices , the solution ? or  2) combine the program of the HTML parser and string regex? 
posted by code
Sat Sep 26 13:23:23 UTC 2015
Whats the ouput?
Download Source Code - for RESTFULL Webservice
posted by serry
Thu Sep 17 07:25:43 UTC 2015
RESTFULL Webservice
posted by Ragupathi
Wed Apr 22 13:20:24 UTC 2015
RestfulWebService Source Code