JSON Serialization Using Jackson

The JAXB API in Java can serialize objects to XML. But, no such API exists for JSON. This is surprising considering JAX-RS requires the support for JSON format. Jackson framework is here to fill that gap. For example, Jersey (an implementation of JAX-RS) uses Jackson as the JSON serializer.

If you plan on doing JSON communication from a RESTful service, use your server’s JAX-RS support. That will be the recommended approach. In some cases, you may need to work with JSON outside the context of a RESTful service. For example, save JSON documents on file. In that case, you can use Jackson. In this post, we will learn how to do that.

Download Jackson

Go to the download page and download these JAR files:

  1. Core
  2. Annotations
  3. Databind

Most applications will use the databind API. That JAR file needs the other two in the list.

Write Test Code

Create a Java project and add all three Jackson JAR files to the build path.

Write a class following this example.

import java.util.ArrayList;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Person {
String name;
int id;
float salary;
public String getName() {
    return name;
public void setName(String name) {
    this.name = name;
public int getId() {
    return id;
public void setId(int id) {
    this.id = id;
public float getSalary() {
    return salary;
public void setSalary(float salary) {
    this.salary = salary;

public Person(String name, int id, float salary) {
    this.name = name;
    this.id = id;
    this.salary = salary;
public Person() {

public static void main(String[] args) {
    try {

        ObjectMapper mapper = new ObjectMapper();
        ArrayList<Person> list = new ArrayList<Person>();

        list.add(new Person("Bugs Bunny", 1, 23.45f));
        list.add(new Person("Daffy Duck", 2, 23.45f));
        list.add(new Person("Samity Sam", 3, 23.45f));

        mapper.writeValue(System.out, list);
    } catch (Exception e) {


When you run this, the program should print this out.

[{"name":"Bugs Bunny","id":1,"salary":23.45},
{"name":"Daffy Duck","id":2,"salary":23.45},
{"name":"Samity Sam","id":3,"salary":23.45}]

Congratulations. You have now developed a JSON application using Jackson.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s