Jackson – Java to JSON & JSON to Java

Converting Java objects to JSON and JSON to java objects is a common function in most apps. Jackson is a Java library that enables you to do so easily.

jackson-java-json

Objectives:

  • How to convert Java object into JSON and back again to Java?
  • How to convert between Generic collection and JSON?
  • How to build Java tree model for JSON?
  • How to configure Jackson using annotations?

Environment & Tools:

  • Eclipse
  • Maven

Libraries:

  • jackson (2.2.2)

Maven dependencies:

<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-core</artifactId>
		<version>2.2.2</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.2.2</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-annotations</artifactId>
		<version>2.2.2</version>
	</dependency>

( 1 ) Simple Conversion POJO/JSON

  • Article.java
package com.hmkcode.vo;

import java.util.LinkedList;
import java.util.List;

public class Article {

	private String title;
	private String url;
	private List<String> categories;
	private List<String> tags;
	
//setters & getters...
	
}

POJO to JSON

ObjectMapper mapper = new ObjectMapper(); 
Article article = new Article(); 
//POJO to JSON
mapper.writeValue(new File("article.json"), article);
System.out.println("json created!");


JSON to POJO

ObjectMapper mapper = new ObjectMapper();
//JSON to POJO
Article article = mapper.readValue(new File("article.json"), Article.class);

( 2 ) Raw Conversion “Generic Collection/JSON”

If you do not want to bind JSON to a specific Java class e.g. Article we can convert JSON into a generic Java Collection object e.g. Map.

//"Raw" Data Binding Example
Map<String,Object> articleMap = mapper.readValue(new File("article.json"), Map.class);

Complete Code:

package com.hmkcode;

import java.io.File;
import java.io.IOException;
import java.util.Map;

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

import com.hmkcode.vo.Article;


public class App 
{
    public static void main( String[] args )
    {

    	ObjectMapper mapper = new ObjectMapper(); 

    	try {
    			
    		//POJO to JSON
			mapper.writeValue(new File("article.json"), createArticle());
			System.out.println("json created!");

			//JSON to POJO
			Article article = mapper.readValue(new File("article.json"), Article.class);
			System.out.println(article);

			//"Raw" Data Binding Example
			Map<String,Object> articleMap = mapper.readValue(new File("article.json"), Map.class);
			System.out.println(articleMap);


    	} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    private static Article createArticle(){

    	Article article = new Article();

    	article.setTitle("Jackson - Java to JSON & JSON to Java");
        article.setUrl("http://hmkcode.com/jackson-java-json");
        article.addCategory("Java");
        article.addTag("Java");
        article.addTag("Jackson");
        article.addTag("JSON");

    	return article;
    }
}

( 3 ) Dealing With Collection<E>

Assume we have a list of articles stored in articles.json.

//Data binding Collection<E>
	List<Article> articles = new LinkedList<Article>();

	articles.add(createArticle());
	articles.add(createArticle());

	mapper.writeValue(new File("articles.json"), articles);

To convert JSON to Collection<Article> “where collection is List or Map”,   we have tow ways:

//( 1 ) Collection<Map>
List result = mapper.readValue(new File("articles.json"), List.class);

//( 2 ) Collection<Artilce>
List result = mapper.readValue(new File("articles.json"), new TypeReference<List<Article>>() { });

There is a major difference between the two ways, the first will convert each item “article” in the artilces.json into Map object while the second will convert each “article” into Article object.

Complete Code:

package com.hmkcode;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.Article;


public class App 
{
    public static void main( String[] args )
    {

    	ObjectMapper mapper = new ObjectMapper(); 

    	try {
    			
			//Data binding Collection<E>
			List<Article> articles = new LinkedList<Article>();

			articles.add(createArticle());
			articles.add(createArticle());

			mapper.writeValue(new File("articles.json"), articles);
			
			//( 1 ) Collection<Map>
			List result = mapper.readValue(new File("articles.json"), List.class);
			System.out.println("Each Article is of type: "+result.get(0).getClass());
			System.out.println(result);

			//( 2 ) Collection<Artilce>
			result = mapper.readValue(new File("articles.json"), new TypeReference<List<Article>>() { });
			System.out.println("Each Article is of type: "+result.get(0).getClass());
			System.out.println(result);
			
			

    	} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    private static Article createArticle(){

    	Article article = new Article();

    	article.setTitle("Jackson - Java to JSON & JSON to Java");
    	article.setUrl("http://hmkcode.com/jackson-java-json");
    	article.addCategory("Java");
    	article.addTag("Java");
    	article.addTag("Jackson");
    	article.addTag("JSON");
    	
    	return article;
    }
}

( 4 ) Tree Model

If you like to deal with JSON as XML use this sample code

package com.hmkcode;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hmkcode.vo.Article;


public class App 
{
    public static void main( String[] args )
    {

    	ObjectMapper mapper = new ObjectMapper(); 

    	try {
    			
    		//create artile.json
			mapper.writeValue(new File("article.json"), createArticle());
		

    		//create artiles.json
			List<Article> articles = new LinkedList<Article>();

			articles.add(createArticle());
			articles.add(createArticle());

			mapper.writeValue(new File("articles.json"), articles);
			
			
			//Tree
			ObjectNode objectRoot = (ObjectNode) mapper.readTree(new File("article.json"));
			Iterator<String> fields = objectRoot.fieldNames();
			String field = "";
			while(fields.hasNext()){
				field = fields.next();
				System.out.println("field: "+field);
			}
			System.out.println("---------------------------------------------------------");

			ArrayNode arrayRoot = (ArrayNode) mapper.readTree(new File("articles.json"));

			Iterator<JsonNode> elements = arrayRoot.elements();
			JsonNode element;

			while(elements.hasNext()){
				element = elements.next();				
				fields = element.fieldNames();
				field = "";
				while(fields.hasNext()){
					field = fields.next();
					System.out.println("field: "+field);
				}

			}

    	} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    private static Article createArticle(){

    	Article article = new Article();

    	article.setTitle("Jackson - Java to JSON & JSON to Java");
    	article.setUrl("http://hmkcode.com/jackson-java-json");
    	article.addCategory("Java");
    	article.addTag("Java");
    	article.addTag("Jackson");
    	article.addTag("JSON");

    	return article;
    }
}

( 5 ) Configuration Annotations

  • @JsonProperty(“name”): rename property name
  • @JsonIgnore: Ignore this property
public class Article {

	private String title;
	@JsonProperty("address")
	private String url;
	private List<String> categories;
        @JsonIgnore
	private List<String> tags;

...
}

Now the ouput “article.json” will as following:

Notice: url is replace with address and tags is not included

{"title":"Jackson - Java to JSON & JSON to Java",
"categories":["Java"],
"address":"http://hmkcode.com/jackson-java-json

Source Code @ GitHub