Java Deserialize Simple Json Sample Code

If you have a Java application that takes in as input a json formatted file, you will need to parse and store the data within that file. There are a couple of options in the Java programming language. First, you could parse file using a simple Json parser and then read each object. We have a Json FileReader Sample Code tutorial that you can take a look at.

The second option is to deserialize the Json input stream into a custom object. The cool part is that Eclipse has a nice utility to then add all of the get (getters) and set (setters) methods to your class object.


Add Java Dependencies

I build projects using Eclipse and Maven. Step one is to add these 3 libraries that manipulate Json data to my pom.xml file so I can use them in my Java program.

<dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.2</version>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.3</version>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.3</version>
    </dependency>


Create Simple Json File

In Eclipse, right click on your project and select New » Folder and call it conf or whatever you desire to call it. Right click on conf folder and select New » Other » Json File. Click Next and then give the new file a name and click Finish. Here is the contents of my new simple Json file.

{
	"firstName" : "Fred",
	"lastName" : "Flinstone",
	"cityName" : "Bedrock",
	"workName" : "Slate Rock and Gravel Company",
	"friendName" : "Barney"
}


Create Main Class

Create a new main class that will hold the variables that correspond to the Json file created in step two. Here is the important part. The name in the name/value pairs in the Json file needs to be the EXACT same name of the String values here.

package com.jcd.java.tutorials.MavenProject;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Flinstones 
{

	@JsonProperty
	private String firstName;
	
	@JsonProperty
	private String lastName;
	
	@JsonProperty
	private String cityName;
	
	@JsonProperty
	private String workName;
	
	@JsonProperty
	private String friendName;

}


Create Process Class

Create a new Java class to actually process the Json file into the Flinstones Object above. When you compile and run, there will be no output to the screen. This is actually the expected output because we don’t have any get() and set() options in our Flinstones Class. Eclipse will do that for us next. In case you didn’t know the terms Marshalling and Unmarshalling, it is talking about marshalling or writing and unmarshalling or reading in terms of processing Java content.

package com.jcd.java.tutorials.MavenProject;

import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;


public class ProcessFlinstones 
{

	public static void main(String[] args) 
	{
		try 
		{
			String fileName = "C:\\Users\\Admin\\Documents\\Workspace\\MavenProject\\conf\\simple.json";
			
			//Point a File object to the Json file for Flinstones
			File flinstonesJsonFile = new File(fileName);
		
			//Create an object mapper
			ObjectMapper mapper = new ObjectMapper();
		
			//Unmarshall the Json to entities
			Flinstones flinstones = mapper.readValue(flinstonesJsonFile, Flinstones.class);
			
		}
		catch(Exception ex) 
		{
			System.out.println("Exception:"+ex.toString());
		}

	}

}


Auto Generate Get & Set Methods

Select the Flinstones.java file and place your cursor just after the last variable (friendName).

Now do [ALT][SHIFT][S] and then click [R] and you will get a popup window. Click on [Select All] button and [OK].



Generate Getters & Setters

Go back and look at your Finstones.java class and you will see a list of all needed get() and set() methods that was auto generated by Eclipse.

package com.jcd.java.tutorials.MavenProject;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Flinstones 
{

	@JsonProperty
	private String firstName;
	
	@JsonProperty
	private String lastName;
	
	@JsonProperty
	private String cityName;
	
	@JsonProperty
	private String workName;
	
	@JsonProperty
	private String friendName;

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

	public String getCityName() {
		return cityName;
	}

	public void setCityName(String cityName) {
		this.cityName = cityName;
	}

	public String getWorkName() {
		return workName;
	}

	public void setWorkName(String workName) {
		this.workName = workName;
	}

	public String getFriendName() {
		return friendName;
	}

	public void setFriendName(String friendName) {
		this.friendName = friendName;
	}

}


Implement Get Methods

package com.jcd.java.tutorials.MavenProject;

import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;


public class ProcessFlinstones 
{

	public static void main(String[] args) 
	{
		try 
		{
			String fileName = "C:\\Users\\Admin\\Documents\\Workspace\\MavenProject\\conf\\simple.json";
			
			//Point a File object to the Json file for Flinstones
			File flinstonesJsonFile = new File(fileName);
		
			//Create an object mapper
			ObjectMapper mapper = new ObjectMapper();
		
			//Unmarshall the Json to entities
			Flinstones flinstones = mapper.readValue(flinstonesJsonFile, Flinstones.class);
			
			System.out.println("First Name: "+flinstones.getFirstName());
			System.out.println("Last Name: "+flinstones.getLastName());
			System.out.println("City Name: "+flinstones.getCityName());
			System.out.println("Work Name: "+flinstones.getWorkName());
			System.out.println("Friend Name: "+flinstones.getFriendName());
		
		}
		catch(Exception ex) 
		{
			System.out.println("Exception:"+ex.toString());
		}

	}

}
First Name: Fred
Last Name: Flinstone
City Name: Bedrock
Work Name: Slate Rock and Gravel Company
Friend Name: Barney


Concluding Comments

This Json Deserialize tutorial use the Jackson Json processor. I really like that Eclipse will auto generate the get and set methods especially when there are numerous variables being used. The Flinstones Json file is a very simple Json formatted file. There are certainly options in Jackson to process more complex Json data with Arrays and even nested Arrays.

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *