Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java JSON Processing (JSON-P) with Example
Next article icon

What is JSON-Java (org.json)?

Last Updated : 17 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

output

 

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.



Next Article
Java JSON Processing (JSON-P) with Example
author
priyarajtt
Improve
Article Tags :
  • Java
  • Java-JSON
Practice Tags :
  • Java

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
    8 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 th
    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 synt
    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 seam
    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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences