Templates by BIGtheme NET

How to read JSON object using JAVA 8

In this article, I will show how read JSON object
using JAVA 8.

Tools Used :

1) eclipse version Luna 4.4.1.

2) Maven 3.3.3

3) JDK 1.8

Simple steps to follow are :

1) Create a simple maven project.

2) Add the dependencies.

3) Write a simple java program to read JSON object from file.

4) Run the program.

Add the given dependency to json api,

<dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1</version>
</dependency>

I have a sample customer json object file with
list of customers,

customer.json

[	
	{
		 "Customer_id": "C101",
		 "firstName": "David",
		 "lastName": "Ronald",
		 "age": 24,
		 "address":
		 {
			 "streetAddress": "21 2nd Street",
			 "city": "New York",
			 "state": "NY",
			 "postalCode": "10021"
		 },
		 "phoneNumber":
		 [
			 {
			   "type": "home",
			   "number": "212 555-1234"
			 },
			 {
			   "type": "fax",
			   "number": "646 555-4567"
			 }
		 ]
	 },
	 {
	 	 "Customer_id": "C102",
		 "firstName": "John",
		 "lastName": "Smith",
		 "age": 25,
		 "address":
		 {
			 "streetAddress": "18 2nd Street",
			 "city": "Oakland",
			 "state": "CA",
			 "postalCode": "10324"
		 },
		 "phoneNumber":
		 [
			 {
			   "type": "home",
			   "number": "123 666-1234"
			 },
			 {
			   "type": "fax",
			   "number": "678 321-4321"
			 }
		 ]
	 }
]

Write a simple java program to read JSON object from file :

Using ClassLoader instance, we can Retrieve a file
with specified name. Simple function that doing this is Here.

/**
 * Retrieve a file with specified name
 */
public Function<String, File> getCustomerFileReader = filename -> {
	ClassLoader cl = getClass().getClassLoader();
	File customer = new File(cl.getResource(filename).getFile());
	return customer;
};

Call this function by passing json file name as parameter
using apply method.

File customer = getCustomerFileReader.apply("customer.json");

We can parse this file object using JSONParser
parser object,

JSONParser parser = new JSONParser();
try (Reader is = new FileReader(customer)) {
	JSONArray jsonArray = (JSONArray) parser.parse(is);

	customers = (Map<String, Customer>) jsonArray.stream().collect(
			Collectors.toMap(key_customer, value_requestString));

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

Pass this file reader instance to parse method of Parser
to get JSONArray object.

Customer Id is the unique value of each customer,
Using this id as key and Customer object as value to Map.

Map customers = null;
customers = (Map) jsonArray.stream().collect(
		Collectors.toMap(key_customer, value_requestString));

Here key_customer and value_requestCustomer are functions,

key_customer, Read the JSON entry and return customer Id and

value_requestCustomer, Read the JSON entry and return the
request Customer.

/**
 * Read the JSON entry and return customer Id
 */
private Function<JSONObject, String> key_customer = c -> (String) ((JSONObject) c)
		.get("Customer_id");

/**
 * Read the JSON entry and return the request Customer
 */
private Function<JSONObject, Customer> value_requestCustomer = json -> {
	Customer cust = new Customer();
	cust.setFirstName((String) json.get("firstName"));
	cust.setLastName((String) json.get("lastName"));
	cust.setAge((Long) json.get("age"));

	final JSONObject address = (JSONObject) json.get("address");
	Address addressObj = new Address((String) address.get("streetAddress"),
			(String) address.get("city"), (String) address.get("state"),
			(String) address.get("postalCode"));

	cust.setAddress(addressObj);

	ArrayList<PhoneNumber> PhoneNumberList = new ArrayList<PhoneNumber>();
	JSONArray phoneNumberJsonArray = (JSONArray) json.get("phoneNumber");
	Iterator<JSONObject> itr = phoneNumberJsonArray.iterator();
	while (itr.hasNext()) {
		final JSONObject phNum = itr.next();
		PhoneNumberList.add(new PhoneNumber((String) phNum.get("type"),
				(String) phNum.get("number")));
	}
	cust.setPhoneNumber(PhoneNumberList);

	return cust;
};

value_requestCustomer is the function that read JSON object and map the individual
customer property values to Customer object.

To print individual customer data, I am using lambda expressions.
I am calling, printit function on each entry set of customers map object.

  
customers.entrySet().stream().forEach(CustomerJsonRead.printit);

printit is a function that takes Entry Set as parameter and print
customer data on console.

/**
 * print a Map.Entry
 */
private static Consumer<Map.Entry<String,Customer>> printit =  
	customer -> {
		final Customer cust = customer.getValue();
		System.out.println("Customer Details are ");
		System.out.println("========================================");
		System.out.println("Customer Key is: " + customer.getKey());
		System.out.println("Customer FirstName is: " + cust.getFirstName());
		System.out.println("Customer LastName is: " + cust.getLastName());
		System.out.println("Customer Age is: " + cust.getAge());
		System.out.println("Customer Address is: ");
		final Address address = cust.getAddress();
		System.out.println("Address StreetAddress is: " + address.getStreetAddress());
		System.out.println("Address City is: " + address.getCity());
		System.out.println("Address State is: " + address.getState());
		System.out.println("Address PostalCode is: " + address.getPostalCode());
		System.out.println("Customer Phonumbers are: ");
		final List<PhoneNumber> phonumbers = cust.getPhoneNumber();
		phonumbers.stream().forEach(phone -> {
			System.out.println("Phonumber type is: "+ phone.getType());
			System.out.println("Phonumber number is: "+ phone.getNumber());
		});
		System.out.println();
	};

I am using Three entity classes, Customer, Address and PhoneNumber.

Customer is the main entity class.
Customer.java

package com.devjavasource.java8.json;

import java.util.List;

public class Customer {

	private String customerId;
	private String firstName;
	private String lastName;
	private Long age;
	private Address address;
	private List<PhoneNumber> phoneNumber;
	
	public String getCustomerId() {
		return customerId;
	}
	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}
	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 Long getAge() {
		return age;
	}
	public void setAge(Long age) {
		this.age = age;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public List<PhoneNumber> getPhoneNumber() {
		return phoneNumber;
	}
	public void setPhoneNumber(List<PhoneNumber> phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
	
}

Address is the sub entity class of Customer.
Address.java

package com.devjavasource.java8.json;

public class Address {

	private String streetAddress;
	private String city;
	private String state;
	private String postalCode;

	Address(final String inStreetAddress, final String inCity,
			final String inState, final String inPostalCode) {
		streetAddress = inStreetAddress;
		city = inCity;
		state = inState;
		postalCode = inPostalCode;
	}

	public String getStreetAddress() {
		return streetAddress;
	}

	public String getCity() {
		return city;
	}

	public String getState() {
		return state;
	}

	public String getPostalCode() {
		return postalCode;
	}
}

PhoneNumber is the sub entity class of Customer.
PhoneNumber.java

package com.devjavasource.java8.json;

public class PhoneNumber {

	private String type;
	private String number;

	PhoneNumber(final String inType, final String inNumber) {
		type = inType;
		number = inNumber;
	}

	public String getType() {
		return type;
	}

	public String getNumber() {
		return number;
	}
}

CustomerJsonRead.java is the main class that reading the customer.json file,
CustomerJsonRead.java

package com.devjavasource.java8.json;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class CustomerJsonRead {
	public static void main(String[] args) {
		CustomerJsonRead customerJsonRead = new CustomerJsonRead();
		Map<String, Customer> customers = customerJsonRead.readCustomerData();

		customers.entrySet().stream().forEach(CustomerJsonRead.printit);
	}

	/**
	 * print a Map.Entry
	 */
	private static Consumer<Map.Entry<String, Customer>> printit = customer -> {
		final Customer cust = customer.getValue();
		System.out.println("Customer Details are ");
		System.out.println("========================================");
		System.out.println("Customer Key is: " + customer.getKey());
		System.out.println("Customer FirstName is: " + cust.getFirstName());
		System.out.println("Customer LastName is: " + cust.getLastName());
		System.out.println("Customer Age is: " + cust.getAge());
		System.out.println("Customer Address is: ");
		final Address address = cust.getAddress();
		System.out.println("Address StreetAddress is: "
				+ address.getStreetAddress());
		System.out.println("Address City is: " + address.getCity());
		System.out.println("Address State is: " + address.getState());
		System.out.println("Address PostalCode is: " + address.getPostalCode());
		System.out.println("Customer Phonumbers are: ");
		final List<PhoneNumber> phonumbers = cust.getPhoneNumber();
		phonumbers.stream().forEach(phone -> {
			System.out.println("Phonumber type is: " + phone.getType());
			System.out.println("Phonumber number is: " + phone.getNumber());
		});
		System.out.println();
	};

	@SuppressWarnings("unchecked")
	public Map<String, Customer> readCustomerData() {
		Map<String, Customer> customers = null;

		File customer = getCustomerFileReader.apply("customer.json");
		JSONParser parser = new JSONParser();
		try (Reader is = new FileReader(customer)) {
			JSONArray jsonArray = (JSONArray) parser.parse(is);

			customers = (Map<String, Customer>) jsonArray.stream().collect(
					Collectors.toMap(key_customer, value_requestCustomer));

		} catch (IOException | ParseException e) {
			e.printStackTrace();
		}
		return customers;
	}

	/**
	 * Retrieve a file with specified name
	 */
	public Function<String, File> getCustomerFileReader = filename -> {
		ClassLoader cl = getClass().getClassLoader();
		File customer = new File(cl.getResource(filename).getFile());
		return customer;
	};

	/**
	 * Read the JSON entry and return customer Id
	 */
	private Function<JSONObject, String> key_customer = c -> (String) ((JSONObject) c)
			.get("Customer_id");

	/**
	 * Read the JSON entry and return the request Customer
	 */
	@SuppressWarnings("unchecked")
	private Function<JSONObject, Customer> value_requestCustomer = json -> {
		Customer cust = new Customer();
		cust.setFirstName((String) json.get("firstName"));
		cust.setLastName((String) json.get("lastName"));
		cust.setAge((Long) json.get("age"));

		final JSONObject address = (JSONObject) json.get("address");
		Address addressObj = new Address((String) address.get("streetAddress"),
				(String) address.get("city"), (String) address.get("state"),
				(String) address.get("postalCode"));

		cust.setAddress(addressObj);

		ArrayList<PhoneNumber> PhoneNumberList = new ArrayList<PhoneNumber>();
		JSONArray phoneNumberJsonArray = (JSONArray) json.get("phoneNumber");
		Iterator<JSONObject> itr = phoneNumberJsonArray.iterator();
		while (itr.hasNext()) {
			final JSONObject phNum = itr.next();
			PhoneNumberList.add(new PhoneNumber((String) phNum.get("type"),
					(String) phNum.get("number")));
		}
		cust.setPhoneNumber(PhoneNumberList);

		return cust;
	};
}

Run the program :

Select CustomerJsonRead, Run As -> Java Application.

Out Put :

Customer Details are 
========================================
Customer Key is: C101
Customer FirstName is: David
Customer LastName is: Ronald
Customer Age is: 24
Customer Address is: 
Address StreetAddress is: 21 2nd Street
Address City is: New York
Address State is: NY
Address PostalCode is: 10021
Customer Phonumbers are: 
Phonumber type is: home
Phonumber number is: 212 555-1234
Phonumber type is: fax
Phonumber number is: 646 555-4567

Customer Details are 
========================================
Customer Key is: C102
Customer FirstName is: John
Customer LastName is: Smith
Customer Age is: 25
Customer Address is: 
Address StreetAddress is: 18 2nd Street
Address City is: Oakland
Address State is: CA
Address PostalCode is: 10324
Customer Phonumbers are: 
Phonumber type is: home
Phonumber number is: 123 666-1234
Phonumber type is: fax
Phonumber number is: 678 321-4321

You can download complete Project, Here

json

*** Venkat – Happy leaning ****