Monday, April 4, 2016

How to convert Java object to / from JSON (Jackson)

In this tutorial, we show you how to use Jackson 1.x data binding to convert Java object to / from JSON.
Note
Jackson 1.x is a maintenance project, please use Jackson 2.x instead.
Note
This tutorial is obsolete, no more update, please refer to the latest Jackson 2 tutorial – Object to / from JSON.

1. Quick Reference

1.1 Convert Java object to JSON, writeValue(...)
Java
ObjectMapper mapper = new ObjectMapper();
User user = new User();

//Object to JSON in file
mapper.writeValue(new File("c:\\user.json"), user);

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(user);
1.2 Convert JSON to Java object, readValue(...)
Java
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'nitin'}";

//JSON from file to Object
User user = mapper.readValue(new File("c:\\user.json"), User.class);

//JSON from String to Object
User user = mapper.readValue(jsonInString, User.class);
P.S All examples are tested with Jackson 1.9.13

2. Jackson Dependency

For Jackson 1.x, it contains 6 separate jars for different purpose, in most cases, you just need jackson-mapper-asl.
pom.xml
Java
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.13</version>
	</dependency>

3. POJO (Plain Old Java Object)

An User object for testing.
User.java
Java
package com.nitin.json;

import java.util.List;

public class User {

	private String name;
	private int age;
	private List<String> messages;

	//getters and setters
}

4. Java Object to JSON

Convert an user object into a JSON formatted string.
JacksonExample.java
Java
package com.nitin.json;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

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

		ObjectMapper mapper = new ObjectMapper();

		//For testing
		User user = createDummyUser();
		
		try {
			//Convert object to JSON string and save into file directly 
			mapper.writeValue(new File("D:\\user.json"), user);
			
			//Convert object to JSON string
			String jsonInString = mapper.writeValueAsString(user);
			System.out.println(jsonInString);
			
			//Convert object to JSON string and pretty print
			jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
			System.out.println(jsonInString);
			
			
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static User createDummyUser(){
		
		User user = new User();
		
		user.setName("nitin");
		user.setAge(33);

		List<String> msg = new ArrayList<>();
		msg.add("hello jackson 1");
		msg.add("hello jackson 2");
		msg.add("hello jackson 3");

		user.setMessages(msg);
		
		return user;
		
	}
}
Output
Bash
//new json file is created in D:\\user.json"

{"name":"nitin","age":33,"messages":["hello jackson 1","hello jackson 2","hello jackson 3"]}

{
  "name" : "nitin",
  "age" : 33,
  "messages" : [ "hello jackson 1", "hello jackson 2", "hello jackson 3" ]
}

5. JSON to Java Object

Read JSON string and convert it back to a Java object.
JacksonExample.java
Java
package com.nitin.json;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

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

		ObjectMapper mapper = new ObjectMapper();

		try {

			// Convert JSON string from file to Object
			User user = mapper.readValue(new File("G:\\user.json"), User.class);
			System.out.println(user);

			// Convert JSON string to Object
			String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"nitin\"}";
			User user1 = mapper.readValue(jsonInString, User.class);
			System.out.println(user1);

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

	}

}
Output
Bash
User [name=nitin, age=33, messages=[hello jackson 1, hello jackson 2, hello jackson 3]]

User [name=nitin, age=33, messages=[msg 1, msg 2]]

6. @JsonView

@JsonView has been supported in Jackson since version 1.4, it lets you control what fields to display.
6.1 A simple class.
Views.java
Java
package com.nitin.json;

public class Views {

	public static class NameOnly{};
	public static class AgeAndName extends NameOnly{};

}
6.2 Annotate on the fields you want to display.
User.java
Java
package com.nitin.json;

import java.util.List;
import org.codehaus.jackson.map.annotate.JsonView;

public class User {

	@JsonView(Views.NameOnly.class)
	private String name;

	@JsonView(Views.AgeAndName.class)
	private int age;
	
	private List<String> messages;

	//getter and setters
}
6.3 Enable the @JsonView via writerWithView().
JacksonExample.java
Java
package com.nitin.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

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

		ObjectMapper mapper = new ObjectMapper();
		//By default all fields without explicit view definition are included, disable this
		mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
		 
		//For testing
		User user = createDummyUser();
		
		try {
			//display name only
			String jsonInString = mapper.writerWithView(Views.NameOnly.class).writeValueAsString(user);
			System.out.println(jsonInString);
			
			//display namd ana age
			jsonInString = mapper.writerWithView(Views.AgeAndName.class).writeValueAsString(user);
			System.out.println(jsonInString);
			
			
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}

	private static User createDummyUser(){
		
		User user = new User();
		
		user.setName("nitin");
		user.setAge(33);

		List<String> msg = new ArrayList<>();
		msg.add("hello jackson 1");
		msg.add("hello jackson 2");
		msg.add("hello jackson 3");

		user.setMessages(msg);
		
		return user;
		
	}
}
Output
Bash
{"name":"nitin"}
{"name":"nitin","age":33}

References

  1. Jackson Project Home @github
  2. Gson – Convert Java object to / from JSON

JSON.simple example – Read and write JSON

JSON.simple, is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).
Note
To convert object to / from JSON, you should consider Jackson or Gson.
In this tutorial, we show you how to use JSON.simple to read and write JSON data from / to a file.

1. JSON.simple Dependency

JSON.simple is available at Maven central repository, just declares following dependency in your pom.xml file.
Markup
  <dependency>
 <groupId>com.googlecode.json-simple</groupId>
 <artifactId>json-simple</artifactId>
 <version>1.1</version>
  </dependency>

2. Write JSON to file

In below example, it write JSON data via JSONObject and JSONArray, and save it into a file named “test.json“.
Java
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

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

 JSONObject obj = new JSONObject();
 obj.put("name", "learnwithnitin.com");
 obj.put("age", new Integer(100));

 JSONArray list = new JSONArray();
 list.add("msg 1");
 list.add("msg 2");
 list.add("msg 3");

 obj.put("messages", list);

 try {

  FileWriter file = new FileWriter("c:\\test.json");
  file.write(obj.toJSONString());
  file.flush();
  file.close();

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

 System.out.print(obj);

     }

}
Output – See content of file named “test.json“.
Bash
{
 "age":100,
 "name":"learnwithnitin.com",
 "messages":["msg 1","msg 2","msg 3"]
}

3. Read JSON from file

Use JSONParser to read above generated JSON file “test.json“, and display each of the values.
Java
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

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

 JSONParser parser = new JSONParser();

 try {

  Object obj = parser.parse(new FileReader("c:\\test.json"));

  JSONObject jsonObject = (JSONObject) obj;

  String name = (String) jsonObject.get("name");
  System.out.println(name);

  long age = (Long) jsonObject.get("age");
  System.out.println(age);

  // loop array
  JSONArray msg = (JSONArray) jsonObject.get("messages");
  Iterator<String> iterator = msg.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }

 } catch (FileNotFoundException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 } catch (ParseException e) {
  e.printStackTrace();
 }

     }

}
Output
Bash
learnwithnitin.com
100
msg 1
msg 2
msg 3

References

  1. JSON.simple official website
  2. JSON.simple encoding JSON example
  3. JSON.simple decoding JSON example

My Profile

My photo
can be reached at 09916017317