Site icon Narayana Tutorial

JSON File to Java Example

JSON File to Java Example

In this article, I am going to show how to parse the JSON file to java object. Suppose we have a JSON file and we need to parse the JSON data into java object to perform the operations

Pre-Requisites

In the eclipse create a maven project as follows.

Address.java

package com.narayanatutorial.json;

public class Address {
	
	private String street;
	private String city;
	private int zipcode;
	
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public int getZipcode() {
		return zipcode;
	}
	public void setZipcode(int zipcode) {
		this.zipcode = zipcode;
	}
	
	@Override
	public String toString(){
		return getStreet() + ", "+getCity()+", "+getZipcode();
	}
}

 

Employee.java

package com.narayanatutorial.json;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.google.gson.annotations.SerializedName;


public class Employee {

	@SerializedName("empID")
	private int id;
	private String name;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private String role;
	private List<String> cities;
	//private Map<String, String> properties;
	private properties properties;
	
	public properties getProperties() {
		return properties;
	}
	public void setProperties(properties properties) {
		this.properties = properties;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	
	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("***** Employee Details *****\n");
		sb.append("ID="+getId()+"\n");
		sb.append("Name="+getName()+"\n");
		sb.append("Permanent="+isPermanent()+"\n");
		sb.append("Role="+getRole()+"\n");
		sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"\n");
		sb.append("Address="+getAddress()+"\n");
		sb.append("Cities="+Arrays.toString(getCities().toArray())+"\n");
		//sb.append("Properties="+getProperties()+"\n");
		sb.append("*****************************");
		
		return sb.toString();
	}
	public List<String> getCities() {
		return cities;
	}
	public void setCities(List<String> cities) {
		this.cities = cities;
	}
//	public Map<String, String> getProperties() {
//		return properties;
//	}
//	public void setProperties(Map<String, String> properties) {
//		this.properties = properties;
//	}
}

 

 

Create JSON File

Create JSON file in the D:\ drive and give the path in java file.

{
  "empID": 100,
  "name": "David",
  "permanent": false,
  "address": {
    "street": "BTM 1st Stage",
    "city": "Bangalore",
    "zipcode": 560100
  },
  "phoneNumbers": [
    123456,
    987654
  ],
  "role": "Manager",
  "cities": [
    "Los Angeles",
    "New York"
  ],
  "properties": {
    "age": "28 years",
    "salary": "1000 Rs"
  }
}

EmployeeGsonExample .java (Reading JSON file)

 

// read JSON file data as String
String fileData = new String(Files.readAllBytes(Paths
.get("D:/employee")));

// parse json string to object
Employee emp1 = gson.fromJson(fileData, Employee.class);

Complete Code

package com.narayanatutorial.json;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class EmployeeGsonExample {

	public static void main(String[] args) throws IOException {
		//Employee emp = createEmployee();

		// Get Gson object
		Gson gson = new GsonBuilder().setPrettyPrinting().create();

		// read JSON file data as String
		String fileData = new String(Files.readAllBytes(Paths
				.get("D:/employee")));

		// parse json string to object
		Employee emp1 = gson.fromJson(fileData, Employee.class);
		
		Address ad=emp1.getAddress();
		properties props=emp1.getProperties();
		
		
		String street=ad.getStreet();
			
		String age=props.getAge();
		
		System.out.println("age:"+age);		
		System.out.println("address:"+street);
		System.out.println("Name:"+emp1.getName()+" "+emp1.getAddress().getStreet());
		// print object data
		//System.out.println("\n\nEmployee Object\n\n" + emp1);

		// create JSON String from Object
		//String jsonEmp = gson.toJson(emp);
	//	System.out.print(jsonEmp);

	}

	public static Employee createEmployee() {

		Employee emp = new Employee();
		emp.setId(100);
		emp.setName("David");
		emp.setPermanent(false);
		emp.setPhoneNumbers(new long[] { 123456, 987654 });
		emp.setRole("Manager");

		Address add = new Address();
		add.setCity("Bangalore");
		add.setStreet("BTM 1st Stage");
		add.setZipcode(560100);
		emp.setAddress(add);

		List<String> cities = new ArrayList<String>();
		cities.add("Los Angeles");
		cities.add("New York");
		emp.setCities(cities);

		Map<String, String> props = new HashMap<String, String>();
		props.put("salary", "1000 Rs");
		props.put("age", "28 years");
		//emp.setProperties(props);

		return emp;
	}
}

GsonReading .java (Reading JSON file)

Just reading JSON from file and displaying the output.

package com.narayanatutorial.json;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class GsonReading {

	
	public static void main(String args[]) throws IOException {
		BufferedReader reader=new BufferedReader(new FileReader("D:/employee"));
		String line="";
		while((line= reader.readLine()) != null) {
			if(line.contains("empID")) {
				String[] arr=line.split(":");
				System.out.println(arr[0]+" "+arr[1]);
			}
			//System.out.println("line:"+line);
		}
	}
}

 

pom.xml

add the following dependency to your project

 <dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.5</version>
</dependency>

 

Complete pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>


  <groupId>com.narayanatutorial.json</groupId>
  <artifactId>Json</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Json</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.6.3</version>
	</dependency>
    
    <!--  Gson dependency -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.5</version>
    </dependency>
    
  </dependencies>
</project>

 

Get complete source code from Github