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:
How to Generate JSON with JsonGenerator in Java?
Next article icon

How to parse JSON in Java

Last Updated : 07 Aug, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

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 array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.

Below is a simple example from Wikipedia that shows JSON representation of an object that describes a person. The object has string values for first name and last name, a number value for age, an object value representing the person’s address, and an array value of phone number objects.

  {      "firstName": "John",      "lastName": "Smith",      "age": 25,      "address": {          "streetAddress": "21 2nd Street",          "city": "New York",          "state": "NY",          "postalCode": 10021      },      "phoneNumbers": [          {              "type": "home",              "number": "212 555-1234"          },          {              "type": "fax",              "number": "646 555-4567"           }      ]   }  

JSON Processing in Java : The Java API for JSON Processing JSON.simple is a simple Java library that allow parse, generate, transform, and query JSON.

Getting Started : You need to download the json-simple-1.1 jar and put it in your CLASSPATH before compiling and running the below example codes.

  • For importing jar in IDE like eclipse, refer here.
  • If you are using maven you may use the following maven link https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

Json-Simple API : It provides object models for JSON object and array structures. These JSON structures are represented as object models using types JSONObject and JSONArray. JSONObject provides a Map view to access the unordered collection of zero or more name/value pairs from the model. Similarly, JSONArray provides a List view to access the ordered sequence of zero or more values from the model.

Write JSON to a file

Let us see an example that writes above JSON data into a file “JSONExample.json”, with help of JSONObject and JSONArray.




// Java program for write JSON to a file
  
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 
    {
        // creating JSONObject
        JSONObject jo = new JSONObject();
          
        // putting data to JSONObject
        jo.put("firstName", "John");
        jo.put("lastName", "Smith");
        jo.put("age", 25);
          
        // for address data, first create LinkedHashMap
        Map m = new LinkedHashMap(4);
        m.put("streetAddress", "21 2nd Street");
        m.put("city", "New York");
        m.put("state", "NY");
        m.put("postalCode", 10021);
          
        // putting address to JSONObject
        jo.put("address", m);
          
        // for phone numbers, first create JSONArray 
        JSONArray ja = new JSONArray();
          
        m = new LinkedHashMap(2);
        m.put("type", "home");
        m.put("number", "212 555-1234");
          
        // adding map to list
        ja.add(m);
          
        m = new LinkedHashMap(2);
        m.put("type", "fax");
        m.put("number", "212 555-1234");
          
        // adding map to list
        ja.add(m);
          
        // putting phoneNumbers to JSONObject
        jo.put("phoneNumbers", ja);
          
        // writing JSON to file:"JSONExample.json" in cwd
        PrintWriter pw = new PrintWriter("JSONExample.json");
        pw.write(jo.toJSONString());
          
        pw.flush();
        pw.close();
    }
}
 
 

Output from file “JSONExample.json” :

  {       "lastName":"Smith",      "address":{          "streetAddress":"21 2nd Street",           "city":"New York",           "state":"NY",           "postalCode":10021      },       "age":25,       "phoneNumbers":[              {              "type":"home", "number":"212 555-1234"              },           {              "type":"fax", "number":"212 555-1234"           }       ],       "firstName":"John"  }  

Note : In JSON, An object is an unordered set of name/value pairs, so JSONObject doesn’t preserve the order of an object’s name/value pairs, since it is (by definition) not significant. Hence in our output file, order is not preserved.

Read JSON from a file

Let us see an example that read JSON data from above created file “JSONExample.json” with help of JSONParser, JSONObject and JSONArray.




// Java program to read JSON from a file
  
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 
    {
        // parsing file "JSONExample.json"
        Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
          
        // typecasting obj to JSONObject
        JSONObject jo = (JSONObject) obj;
          
        // getting firstName and lastName
        String firstName = (String) jo.get("firstName");
        String lastName = (String) jo.get("lastName");
          
        System.out.println(firstName);
        System.out.println(lastName);
          
        // getting age
        long age = (long) jo.get("age");
        System.out.println(age);
          
        // getting address
        Map address = ((Map)jo.get("address"));
          
        // iterating address Map
        Iterator<Map.Entry> itr1 = address.entrySet().iterator();
        while (itr1.hasNext()) {
            Map.Entry pair = itr1.next();
            System.out.println(pair.getKey() + " : " + pair.getValue());
        }
          
        // getting phoneNumbers
        JSONArray ja = (JSONArray) jo.get("phoneNumbers");
          
        // iterating phoneNumbers
        Iterator itr2 = ja.iterator();
          
        while (itr2.hasNext()) 
        {
            itr1 = ((Map) itr2.next()).entrySet().iterator();
            while (itr1.hasNext()) {
                Map.Entry pair = itr1.next();
                System.out.println(pair.getKey() + " : " + pair.getValue());
            }
        }
    }
}
 
 

Output:

  John  Smith  25  streetAddress : 21 2nd Street  postalCode : 10021  state : NY  city : New York  number : 212 555-1234  type : home  number : 212 555-1234  type : fax  


Next Article
How to Generate JSON with JsonGenerator in Java?

G

Gaurav Miglani
Improve
Article Tags :
  • Java
  • Java-JSON
Practice Tags :
  • Java

Similar Reads

  • How to Start Learning Java?
    Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming cons
    8 min read
  • StAX XML Parser in Java
    This article focuses on how one can parse a XML file in Java.XML : XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. That’s why, the design goals of XML emphasize simplicity, generality, and usability acros
    6 min read
  • How to Run Java Program?
    Java is a popular, high-level, object-oriented programming language that was developed by James Gosling and his team at Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s. It is widely used for developing various kinds of software, including web applications, desktop applications, m
    2 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
  • JAVA DOM Parser
    IntroductionJava is one of the most popular programming languages that is applicable to different purposes, starting from the web environment and ending with business-related ones. XML processing is one of the most important facets in the competence of Java as a language. The principal data exchange
    8 min read
  • What is JSON-Java (org.json)?
    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
    5 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 Setup Jackson in Java Application?
    JSON(Javascript Object Notation) is the most popular format for the exchange of data in the world of web applications. The browsers can easily parse json requests and convert them to javascript objects. The servers parse json requests, process them, and generates a new json response. JSON is self-de
    7 min read
  • How to Install GSON Module in Java?
    Google GSON is a simple Java-based serialization/deserialization library to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java Object. It is a reliable, fast, and efficient extension to the Java standard library. It's also highly o
    3 min read
  • How to Iterate Any Map in Java?
    In Java, a Map is a data structure that is used to store key-value pairs. Understanding how to iterate over the elements of a map plays a very important role. There are 5 ways to iterate over the elements of a map, and in this article, we are going to discuss all of them. Note: We cannot iterate ove
    5 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