Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Convert Java Object To / From JSON using Jackson example

In this example we are going to see how to conver a Java Object to JSON representation using Jackson. Jackson in a high performance JSON parser and processor java project.

1. Jackson Library

The complete Jackson library consists of 6 jar files that are used for many diffident operation. In this example we are going to need just one, mapper-asl.jar. If you want to install the full library to your project you can download and use jackson-all-*.jar that includes all the jars. You can download them from the Jackson Download Page.

If your using Maven in your project you just have to add the following repository and dependency in your pom.xml.

 <repositories>
	<repository>
		<id>codehaus</id>
		<url>http://repository.codehaus.org/org/codehaus</url>
	</repository>
  </repositories>

  <dependencies>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-all-*</artifactId>
		<version>*</version>
	</dependency>
  </dependencies>

2. Java Object

This is the class we are going to use for the demonstration:

Student.java:

package com.javacodegeeks.java.core;

public class Student {

    private int id;
	private String firstName;
	private String lastName;
	private int age;

	public Student(){

	}

	public Student(String fname, String lname, int age, int id){
		this.firstName = fname;
		this.lastName  = lname;
		this.age        = age;
		this.id         = id;
	}

	public void setFirstName(String fname) {
		this.firstName = fname;
	}

	public String getFirstName() {
		return this.firstName;
	}

	public void setLastName(String lname) {
		this.lastName = lname;
	}

	public String getLastName() {
		return this.lastName;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getAge() {
		return this.age;
	}

	public void setId(int id){
		this.id = id;
	}

	public int getId(){
		return this.id;
	}

	@Override
	public String toString() {
		return new StringBuffer(" First Name : ").append(this.firstName)
				.append(" Last Name : ").append(this.lastName).append(" Age : ").append(this.age).append(" ID : ").append(this.id).toString();
	}

}

3. Convert Java Object to JSON represenation

JacksonJSONExample.java:

package com.javacodegeeks.java.core;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonJSONExample {

	private static final String jsonFilePath= "C:\\Users\\nikos7\\Desktop\\filesForExamples\\student.json";

	public static void main(String[] args) {

		Student student = new Student("Jacl", "Freeman", 32, 100);

		ObjectMapper mapper = new ObjectMapper();

		try {

			File jsonFile = new File(jsonFilePath);

			mapper.writeValue(jsonFile, student);

			//System.out.println(mapper.writeValueAsString(student));

		} catch (JsonGenerationException ex) {

			ex.printStackTrace();

		} catch (JsonMappingException ex) {

			ex.printStackTrace();

		} catch (IOException ex) {

			ex.printStackTrace();

		}
	}
}

student.json:

{"id":100,"firstName":"Jacl","lastName":"Freeman","age":32}

4. Convert a JSON representation to Java Object

JSONToJavaObjectJacksonExample.java:

package com.javacodegeeks.java.core;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JSONToJavaObjectJacksonExample {

	private static final String jsonFilePath= "C:\\Users\\nikos7\\Desktop\\filesForExamples\\student.json";

	public static void main(String[] args) {

		ObjectMapper mapper = new ObjectMapper();

		try {
			File jsonFile = new File(jsonFilePath);

			Student student = mapper.readValue(jsonFile, Student.class);

			System.out.println(student);

		} catch (JsonGenerationException e) {

			e.printStackTrace();

		} catch (JsonMappingException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}
	}
}

Output:

 First Name : Jacl Last Name : Freeman Age : 32 ID : 100

 
This was an example on how to convert Java Object To / From JSON using Jackson.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books