Jackson – Java JSON Processor

JSON stands for Java Script Object Notation. JSON is a format for efficient transfer of data across Platform. To manipulate JSON in Java, we have many processors. One of such JSON processor in Java is Jackson. Jackson is a high performance JSON processor. Reading, Writing and modifying contents is made easy in Java using the Jackson. Jackson provides with classes and methods to perform these operations. There are so many programmers who want to learn and implement a JSON program in Java. This is a step-by-step guide to read from and write into a JSON file from Java using Jackson.

JSON & Jackson

JSON is based on Java Script. JSON works well with objects. These two factors shall be the spear-head for JSON to gain entry in to the web world, where interoperability is the key to sustain. Since it resembles a JavaScript object, we can use functions like eval() to create or parse the JSON values. In the JSON web site, it is claimed that,

JSON is built on two structures,

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence

Reference : http://www.json.org/

The JSON, as it is evolving in to a giant in this new web world, where it is used from simple AJAX response to RESTful web services, we must also look into how the programming languages handle and generate these files. Jackson easily fits into this requirement. Jackson has capability to read and write into a JSON file from Java, and most stunningly it is capable of creating a JSON from a Java object and read a JSON file back into a Java object. Jackson is packaged in to a jar file which contains all necessary data required for using JSON. We shall discuss about a couple of important classes and its methods to write and read a JSON file in Jackson.

How to read a JSON fil?

Reading a JSON file is far simpler in Jackson. All we need is the Jackson-all-1.8.5.jar file. Let us take a simple JSON file as below and see how Jackson processor is able to read from it.

<strong>CountryFile.json</strong>
{
"Name":"United States of America",
"Capital":"Washington, D.C.",
"States":["California","Maryland","Florida"]
}

This JSON has two kinds of data in it. One is a simple data where key values are present and the other is an array data. The Name holds a string value, the Capital holds a string value and the States hold multiple values in it. Let us create a simple Java method named readJSON() to read this file.

In the Jackson library we have a class named as ObjectMapper. This class holds almost all the important methods required for reading and writing a JSON file. This ObjectMapper class has the method readValue(). This method takes various parameters. Typically it takes the file name and the Java collection into which the JSON file must be mapped. Since the data in the JSON are all key value pairs, Map collection would be a better candidate to hold the JSON values in Java, so for this method we shall pass our CountryFile.json as a file and Map.class as our collection. So the code shall look as below.

ObjectMapper mapper = new ObjectMapper();
Map&lt;String,Object&gt; userData = mapper.readValue(new File("CountryFile.json"), Map.class);

As this line executes, the data from the JSON would have been mapped into the userData object. As this is a map, to get the values from it, we can use the entrySet method.

Set mySet = userData.entrySet();

An iterator can be used on this mySet to get each value that is stored inside the file as object which we can use it for processing further.

for (Iterator iterator = mySet.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println(object);
}

Now we have successfully read the values from the JSON file and printed it.

Write a JSON file

Let us try to create and write a JSON file from Java. Since all the data are key value pairs in JSON, we shall have our data in a Map and try to write it. So first we will create a map and populate the data into it.

Map<String,Object> country = new HashMap<String, Object>();

country.put("Name","United States of America");
country.put("Capital", "Washington, D.C.");

Set states = new HashSet();
states.add("Florida");
states.add("Maryland");
states.add("California");

country.put("States",states);

In this above snippet, we have created a Map named country and added values to it. Moreover we have also created a Set named as states and added values to it.

To write a map into file all we require is the ObjectMapper class and the writeValue() method of it. The writeValue() method takes two parameters namely the object that must be written and the name of the file in which the data must be written.

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("CountryFile.json"), country);

On execution the above line we would be getting JSON file created as CountryFile.json and all our data written into it.

It is important to note the all the values in the map was written as key value pair in the JSON file. The value was written as multivalued element in the JSON. This way we can make use of various methods of the Jackson library to create/read different kinds of elements in the JSON file.
So the final output file would look like,
CountryFile.json

{
"Name":"United States of America",
"Capital":"Washington, D.C.",
"States":["California","Maryland","Florida"]
}

Full code

package demo.jackson;
import java.io.File;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;

public class JacksonDemo {

	public void writeJSON() throws Exception {

		Map&lt;String,Object&gt; country = new HashMap&lt;String, Object&gt;();

		country.put("Name","United States of America");
		country.put("Capital", "Washington, D.C.");

		Set&lt;String&gt; states = new HashSet&lt;String&gt;();
		states.add("Florida");
		states.add("Maryland");
		states.add("California");

		country.put("States",states);

		ObjectMapper mapper = new ObjectMapper();
		mapper.writeValue(new File("CountryFile.json"), country);

		System.out.println("**success***");
	}

	public void readJSON() throws Exception {

		ObjectMapper mapper = new ObjectMapper();
		Map&lt;String,Object&gt; userData =
                    mapper.readValue(new File("CountryFile.json"), Map.class);

		Set mySet = userData.entrySet();

		for (Iterator iterator = mySet.iterator(); iterator.hasNext();) {
			Object object = (Object) iterator.next();
			System.out.println(object);
		}
	}

	public static void main(String[] args){
		try {
			JacksonDemo myPgm = new JacksonDemo();
			myPgm.writeJSON();
			myPgm.readJSON();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Conclusion

We have discussed how to read and write JSON from Java using the Jackson processor. Don’t sit back and assume that this is all Jackson can do, we have just now hit the tip of an iceberg, there are lots of things to explore inside the Jackson, which offers multiple varieties to process JSON files.

Comments

comments

Speak Your Mind

*