What is JSON-Java (org.json)?
Last Updated :
17 Jul, 2022
JSON(Javascript Object Notation) is a lightweight format of data exchange and it is independent of language. It is easily read and interpreted by humans and machines. Hence nowadays, everywhere JSON is getting used for transmitting data. Let us see how to prepare JSON data by using JSON.org JSON API in java
- JSON.simple is a library in java is used that allows parsing/generating/transforming/querying JavaScript Object Notation, etc.,
- Necessary jar file: json-simple-1.1.jar. It has to be available in the classpath
- In Maven-driven projects it should be present in pom.xml as follows
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
We can store the items in the form of JSONObject or JSONArray. JSONArray is nothing but the collection of multiple JSON Objects. A sample JSON object can be viewed as follows
Let us see the ways how to create a JSON object
JsonEncodeExample.java
Java
// Importing JSON simple library
import org.json.simple.JSONObject;
// Creating a public class
public class JsonEncodeExample {
// Calling the main method
public static void main(String[] args)
{
// Creating an object of JSON class
JSONObject geekWriterObject = new JSONObject();
// Entering the values using the created object
geekWriterObject.put("geekWriterId",
new Integer(100));
geekWriterObject.put("geekWritterName",
"GeekAuthor1");
geekWriterObject.put("status", new Boolean(true));
geekWriterObject.put("publishedArticlesIn",
"Java,Python");
// Printing the values through the created object
System.out.print(geekWriterObject);
}
}
On running the above program we can see the output as
If we beautify this using the online JSON viewer, we will get the same output as appeared in the sample JSON
JsonDecodeExample.java
Java
// importing JSON simple libraries
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
// Creating a public class
public class JsonDecodeExample {
// calling the main method
public static void main(String[] args)
{
// creating an object of JSONparser
JSONParser jsonParser = new JSONParser();
// defining and assigning value to a string
String sampleString = "[28,{\"38\":{\"48\":{\"58\":{\"68\":[78,{\"88\":98}]}}}}]";
try {
Object object = jsonParser.parse(sampleString);
// creating a JSON array
JSONArray array = (JSONArray)object;
System.out.println("The array's first element is");
// always start the index by 0
System.out.println(array.get(0));
System.out.println("The array's second element is");
System.out.println(array.get(1));
System.out.println();
// creating a JSON object
JSONObject jsonObject = (JSONObject)array.get(1);
System.out.println("Value of \"38\"");
System.out.println(jsonObject.get("38"));
}
catch (ParseException pr) {
System.out.println("The elements position is: "
+ pr.getPosition());
System.out.println(pr);
}
}
}
On running the above program, we get the output as follows
Let us see how the JSONObject and JSONArray can be written in an external file named "author.json" via
JSONWriteExample.java
Java
// importing java simple libraries and JSON libraries
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JSONWriteExample {
public static void main(String[] args)
throws FileNotFoundException
{
// Json object is created
JSONObject jsonObject = new JSONObject();
// Adding data using the created object
jsonObject.put("firstName", "Rachel");
jsonObject.put("lastName", "Green");
jsonObject.put("age", 30);
jsonObject.put("noOfPosts", 100);
jsonObject.put("status", "active");
// LinkedHashMap is created for address data
Map addressMap = new LinkedHashMap(4);
addressMap.put("road", "MG Road Cross cut Street");
addressMap.put("city", "Bangalore");
addressMap.put("state", "Karnataka");
addressMap.put("pinCode", 560064);
// adding address to the created JSON object
jsonObject.put("addressOfAuthor", addressMap);
// JSONArray is created to add the phone numbers
JSONArray phoneNumberJsonArray = new JSONArray();
addressMap = new LinkedHashMap(2);
addressMap.put("presentAt", "home");
addressMap.put("phoneNumber", "1234567890");
// adding map to list
phoneNumberJsonArray.add(addressMap);
addressMap = new LinkedHashMap(2);
addressMap.put("type2", "fax1");
addressMap.put("no1", "6366182095");
// map is added to the list
phoneNumberJsonArray.add(addressMap);
// adding phone numbers to the created JSON object
jsonObject.put("phoneNos", phoneNumberJsonArray);
// the JSON data is written into the file
PrintWriter printWriter = new PrintWriter("author.json");
printWriter.write(jsonObject.toJSONString());
printWriter.flush();
printWriter.close();
}
}
On running the above program, we can see the "author.json" file is created in the mentioned location and its contents are as follows (The output is beautified and shown here as reference)
Let us see how to read the JSON via
JSOnReadExample.java
Java
// importing JSON simple libraries
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
public class JSONReadExample {
public static void main(String[] args) throws Exception
{
// The file JSON.json is parsed
Object object = new JSONParser().parse(new FileReader("author.json"));
// objc is convereted to JSON object
JSONObject jsonObject = (JSONObject)object;
// obtaining the fname and lname
String firstName = (String)jsonObject.get("firstName");
String lastName = (String)jsonObject.get("lastName");
System.out.println("FirstName = " + firstName);
System.out.println("LastName = " + lastName);
// age is obtained
long ageOfAuthor = (long)jsonObject.get("age");
System.out.println("Age = " + ageOfAuthor);
// address is obtained
System.out.println("Address details:");
Map addressOfAuthor = ((Map)jsonObject.get("addressOfAuthor"));
// iterating through the address
Iterator<Map.Entry> iterator = addressOfAuthor.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pair1 = iterator.next();
System.out.println(pair1.getKey() + " : "+ pair1.getValue());
}
// phone numbers are obtained
System.out.println("Phone Number details:");
JSONArray phoneNumberJSONArray = (JSONArray)jsonObject.get("phoneNos");
// iterating phoneNumbers
Iterator phoneNumberIterator = phoneNumberJSONArray.iterator();
while (phoneNumberIterator.hasNext()) {
iterator = ((Map)phoneNumberIterator.next())
.entrySet()
.iterator();
while (iterator.hasNext()) {
Map.Entry pair1 = iterator.next();
System.out.println(pair1.getKey() + " : "
+ pair1.getValue());
}
}
}
}
On running the program, we can see the output as follows:
Conclusion
JSON is a lightweight easily readable, understandable, and iteratable transportation medium. Nowadays it is the output mechanism that got followed in any REST API calls. This way of mechanism is easily understood in android and IOS development and hence one JSON output of REST API call serves the purpose of many communications.
Similar Reads
Java JSON Processing (JSON-P) with Example
JSON (JavaScript Object Notation) is text-based lightweight technology. Nowadays it is a dominant and much-expected way of communication in the form of key-value pairs. Â It is an easier way of transmitting data as it is having nice formatted way. We can nest the objects and also can provide JSON arr
7 min read
What is JSON Array?
JSON Array is almost the same as JavaScript Array. JSON array can store values of type string, array, boolean, number, object, or null. In JSON array, values are separated by commas. Array elements can be accessed using the [] operator.JSON Array is of different types. Let's understand them with the
5 min read
What is JSON?
JSON (JavaScript Object Notation) is a lightweight text-based format for storing and exchanging data. It is easy to read, write, and widely used for communication between a server and a client.Key points:JSON stores data in key-value pairs.It is language-independent but derived from JavaScript synta
3 min read
What is JSON text ?
JSON text refers to a lightweight, human-readable format for structuring data using key-value pairs and arrays. It is widely used for data interchange between systems, making it ideal for APIs, configuration files, and real-time communication.In todayâs interconnected digital world, data flows seaml
4 min read
What is JSONB in PostgreSQL?
PostgreSQL is a powerful object-relational database management system that excels at handling structured and semi-structured data, especially through its support for JSONB. JSONB (Binary JSON) allows efficient storage and querying of JSON data and making it ideal for applications that require quick
5 min read
How to parse JSON in Java
JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An arr
4 min read
How to Generate JSON with JsonGenerator in Java?
The JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is lightweight, flexible, and faster than XML, which is the reason that it is used widely for data interchange between server and client. If you ever work on J
15 min read
Working with JSON Data in Java
JSON stands for JavaScript Object Notation which is a lightweight text-based open standard designed which is easy for human-readable data interchange. In general, JSON is extended from JavaScript. JSON is language-independent and It is easy to read and write. The file extension of JSON is .json. Exa
3 min read
How to read JSON files in R
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read for humans as well as machines to parse and generate. It's widely used for APIs, web services and data storage. A JSON structure looks like this:{ "name": "John", "age": 30, "city": "New York"}JSON data c
2 min read
What is JSON-RPC in Ethereum?
JSON-RPC is used to communicate with an application that you running on your computer. It uses the HTTP protocol for remote procedure calls and JSON for data representation. It's a stateless, lightweight RPC protocol that's written in JavaScript. For example, JSON-RPC makes communication between cli
6 min read