JSON with Java (Jackson)

Prerequisites:
Tomcat 7 with Eclipse Juno

Scenario:
Several POJOs (player, team, club)
Mockup data
Create JSON Object in Java using Jackson
Use a simple JSP to offer the JSON data

Download Jackson:
Download the latest jars from http://wiki.fasterxml.com/JacksonDownload (in my case version 2.1.4)

Create a new Dynamic Web Project:

Eclipse new dynamic web project

Eclipse new dynamic web project

Add the downloaded JARs to your project:

Add Jackson Jars

Add Jackson Jars


Add the JARs to your classpath:

Add Jars to Class Path

Add Jars to Class Path

Ok now we are ready to start programming our POJOs.
We will have a club, this club has several teams and players are part of this teams. Therefore I create a package named pojo.

club.java

package pojo;

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

public class Club {

	private String clubname;
	private List teams = new ArrayList();

	public void addTeam(Team team){
		this.teams.add(team);
	}

	public String getClubname() {
		return clubname;
	}

	public void setClubname(String clubname) {
		this.clubname = clubname;
	}

	public List getTeams() {
		return teams;
	}

	public void setTeams(List teams) {
		this.teams = teams;
	}

}

team.java

package pojo;

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

public class Team {

	private String teamname;
	private List players = new ArrayList();

	public void addPlayer(Player player) {
		this.players.add(player);
	}

	public String getTeamname() {
		return teamname;
	}

	public void setTeamname(String teamname) {
		this.teamname = teamname;
	}

	public List getPlayers() {
		return players;
	}

	public void setPlayers(List players) {
		this.players = players;
	}

}

player.java

package pojo;

public class Player {

	private String firstname;
	private String lastname;

	public Player(String firstname, String lastname){
		this.firstname = firstname;
		this.lastname = lastname;
	}

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

The next step is to create our data. I defined an interface named IDao and a class named DaoMockup.java to build some mockup data in package dao.

IDao.java

package dao;

import pojo.Club;

/**
 * @author duckout.de
 * Using an interface makes it easy to encapsulate the data.
 *
 */
public interface IDao {

	public Club getClubData();

}

DaoMockup.java

package dao;

import pojo.Club;
import pojo.Player;
import pojo.Team;

public class DaoMockup implements IDao {

	@Override
	public Club getClubData() {

		// Create your favorite club :)
		Club eintrachtFrankfurt = new Club();
		eintrachtFrankfurt.setClubname("Eintracht Frankfurt");

		// Create the teams of the club
		Team firstFootballTeam = new Team();
		firstFootballTeam.setTeamname("First Team");

		Team secondFootballTeam = new Team();
		secondFootballTeam.setTeamname("Second Team");

		// Add teams to the club
		eintrachtFrankfurt.addTeam(firstFootballTeam);
		eintrachtFrankfurt.addTeam(secondFootballTeam);

		// Create some players for the first team
		Player nikolov = new Player("Oka", "Nikolov");
		firstFootballTeam.addPlayer(nikolov);

		Player trapp = new Player("Kevin", "Trapp");
		firstFootballTeam.addPlayer(trapp);

		Player jung = new Player("Sebastian", "Jung");
		firstFootballTeam.addPlayer(jung);

		Player rode = new Player("Sebastian", "Rode");
		firstFootballTeam.addPlayer(rode);

		Player meier = new Player("Alexander", "Meier");
		firstFootballTeam.addPlayer(meier);

		Player aigner = new Player("Stefan", "Aigner");
		firstFootballTeam.addPlayer(aigner);

		Player schwegler = new Player("Pirmin", "Schwegler");
		firstFootballTeam.addPlayer(schwegler);

		Player oczipka = new Player("Bastian", "Oczipka");
		firstFootballTeam.addPlayer(oczipka);

		// Create some players for the second team
		Player ronaldo = new Player("Cristiano", "Ronaldo");
		secondFootballTeam.addPlayer(ronaldo);

		Player messi = new Player("Lionel", "Messi");
		secondFootballTeam.addPlayer(messi);

		Player zidane = new Player("Zinédine", "Zidane");
		secondFootballTeam.addPlayer(zidane);

		return eintrachtFrankfurt;
	}

}

So far we didn’t do anything with Jackson. Since we added the specific JARs to our project and class path we are able to use the framework.
The following class will format our mock data into a JSON formatted String.
Json.java

package json;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import dao.DaoMockup;
import dao.IDao;

public class Json {

	public String createJson() {

		ObjectMapper objectMapper = new ObjectMapper();
		Writer stringWriter = new StringWriter();

		// use the mockup dao
		IDao dao = new DaoMockup();

		try {
		// writeValue(OutputStream out, Object value):
		//Method that can be used to serialize any 
		//Java value as JSON output, 
                //using output stream provided
			objectMapper.writeValue(stringWriter, dao.getClubData());
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return stringWriter.toString();
	}

}

To provide the JSON formatted data we create a JSP called jsonProvider.jsp

<%@page import="json.Json"%>;
<%
	Json json = new Json();
	out.print(json.createJson());
%>

You can now run the application on your tomcat server (http://localhost:8080/de.duckout.json/jsonProvider.jsp). There your will find the JSON formatted data:

Json Provider Jsp

Json Provider Jsp

Sources:

http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html

Posted on by Monte in Java 4 Comments

4 Responses to JSON with Java (Jackson)

  1. Nico

    What an amazing article!

  2. mitja

    This can be much more simpler. See my gist :
    https://gist.github.com/gustinmi/5020943.

  3. Cristiano Ronaldo

    Hey, you have my name wrong, it’s Cristiano not Christiano.

  4. Monte

    Thanks mitja, thanks Cristiano!

Add a Comment