Web Programming TutorialsLearn How to Write a Program on JSON with Java

Learn How to Write a Program on JSON with Java

In this chapter, we are going to learn about the encoding and decoding of JSON objects by using JSON.simple API and JAVA as a programming language. Here, we are going to use eclipse and the maven plugin to develop and build the JAVA project respectively.

Environment Set up
Let’s start working with the environment set up for JSON with Java project for which the following are the steps.

• Step 1: – Download the maven plugin [apache-maven-3.5.0] from the following link. Unzip the downloaded package under the following path [C:\work\app].

Maven Plugin Download Link

https://maven.apache.org/download.cgi

• Step 2: – Set up the following windows operating system environment variables as M2_REPO, PATH M2_HOME, and MAVEN_OPTS as shown below.

S No

Variable Name

Variable value

1.

M2_REPO

C:\Users\Aparajita\.m2\repository

2.

M2_HOME

C:\work\app\apache-maven-3.5.0

3.

PATH

%Path%;C:\work\app\apache-maven-3.5.0\bin;

4.

MAVEN_OPTS

-Xms256m -Xmx512m

• Step 3: – Open a new Maven Project in eclipse and navigate in eclipse as New  others… Maven Project as shown below.
eclipse and navigate• Step 4: – In this step, you need to enter the group id, artifact id and version field as the Archetype parameters are required for a maven project as shown below.
json-with-java• Step 5: – Open pom.xml file for the maven project ‘json-with-java’ which you have just created and add the maven repository URL for json-simple-1.1.1.jar [JSON.simple].

<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.eduonix</groupId>
	<artifactId>json-with-java</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>json-with-java</name>
	<url>http://maven.apache.org</url>

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

	<repositories>
		<repository>
			<id>com.googlecode.json-simple</id>
			<url>https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.googlecode.json-simple</groupId>
			<artifactId>json-simple</artifactId>
			<version>1.1.1</version>
		</dependency>
	</dependencies>
</project>

• Step 6: – Maven tool will automatically download json-simple-1.1.1.jar API and set the project build path for the Java/J2EE application as shown below.
File structure for Maven projectAt this point, the installation of the JSON.simple API has completed and you are ready to implement it in your Java project.

JSON and Java entities Mappings
The following entities are mapped through JSON.simple API. As shown below, on the left hand side are the Java entities and on the right hand side are JSON entities. These entities are inter-converted from one form to another and vice versa during encoding and decoding.

S No.

JAVA

JSON

1.

java.lang.String

string

2.

java.lang.Number

number

3.

java.lang.Boolean

True | false

4.

null

null

5.

java.util.List

array

6.

java.util.Map

object

Java Object to JSON Encoding
In the following example, we are going to encode a JSON object by using JSONObject. JSONObject is a subclass of java.util.HashMap where no ordering is provided. We can also use the strict ordering of elements as well with the help of JSONValue.toJSONString (map) method i.e. by implementation of java.util.LinkedHashMap.

package com.eduonix.json_with_java;

import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONObject;

/**
 * 
 * @author Aparajita
 *
 */
public class JSONEncodingExample {

	public static void main(String[] args) {

		Map<Object, Object> dataMap = new HashMap<Object,Object>();

		dataMap.put ("name", "Aparajita");
		dataMap.put ("age", new Integer(25));
		dataMap.put ("Salary", new Double(5000.99));
		dataMap.put ("employed", new Boolean(true));
		dataMap.put ("job", "Freelancing");
		
		JSONObject jsonObj = new JSONObject(dataMap);

		System.out.print("Encoding from JAVA to JSON: ");
		System.out.print(jsonObj);
	}
}

Output
When we compile and execute above JAVA program, we can observe that Java Object i.e. HashMap has encoded into JSONObject, which we have displayed on the console as shown below.

Encoding from JAVA to JSON: {"name":"Aparajita","Salary":5000.99,"job":"Freelancing","age":25,"employed":true}

JSON to Java Object Decoding
In the following example, we are going to use JSONObject and JSONArray from JSON.simple API. JSONObject works as a java.util.Map whereas JSONArray works as a java.util.List. Therefore, we are going to use both Map and List in order to access them.

package com.eduonix.json_with_java;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
 * 
 * @author Aparajita
 *
 */
public class JSONDecodingExample {
	
	public static void main(String[] args) {

		JSONParser parser = new JSONParser();
		String str = "[ 0 , {\"1\" : { \"2\" : {\"3\" : {\"4\" : [5, { \"6\" : { \"7\" : 8 } } ] } } } } ]";

		try {
			Object obj = parser.parse(str);
			JSONArray array = (JSONArray) obj;

			System.out.println("2nd Array element: ");
			System.out.println(array.get(1));
			System.out.println();

			JSONObject object2 = (JSONObject) array.get(1);
			System.out.println("Field \"1\"");
			System.out.println(object2.get("1"));

			str = "{}";
			obj = parser.parse(str);
			System.out.println(obj);

			str = "[6,]";
			obj = parser.parse(str);
			System.out.println(obj);

			str = "[6,,3]";
			obj = parser.parse(str);
			System.out.println(obj);
			
		} catch (ParseException parseExp) {

			System.out.println("Exception position: " + parseExp.getPosition());
			System.out.println(parseExp);
		}
	}
}

Output
When we compile and execute above JAVA program, we can observe the output on the console as shown below.

2nd Array element: 
{"1":{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}
{}
[6]
[6,3]

Source code for How to Write a Program on JSON with Java

Conclusion: –
In this chapter, we discussed about the encoding and decoding of JSON objects by using JSON.simple API and JAVA as a programming language along with their implementation with the help of various suitable examples.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -