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 parse JSON in Java
Next article icon

Working with JSON Data in Java

Last Updated : 26 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Example – JSON format 

In the below given example, you will see how you can store values in JSON format. Consider student information where Stu_id, Stu_Name, Course is an entities you need to store then in JSON format you can store these values in key values pair form. Let’s have a look.

{    "Student": [            {          "Stu_id"   :  "1001",          "Stu_Name" :  "Ashish",          "Course"   :  "Java",       },            {          "Stu_id"   :  "1002",          "Stu_Name" :  "Rana",          "Course"   :  "Advance Java",       }    ] }

It is the method by which we can access means read or write JSON data in Java Programming Language. Here we simply use the json.simple library to access this feature through Java means we can encode or decode JSON Object using this json.simple library in Java Programming Language. Now, the json.simple package for Java contains the following files in it. So to access we first have to install json.simple package.
 
For installation first, we required to set the json-simple.jar classpath or add the Maven dependency in different cases.

Step 1: Download the json.simple using this link: Download link for json.sample

Step 2: There is one more method to add the Maven dependency, so for that, we have to add the code given below to our pom.xml file.

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

The above-downloaded .jar file contains these Java source files in it : 

// .jar file  META-INF/MANIFEST.MF org.json.simple.ItemList.class org.json.simple.JSONArray.class org.json.simple.JSONAware.class org.json.simple.JSONObject.class org.json.simple.JSONStreamAware.class org.json.simple.JSONValue.class org.json.simple.parser.ContainerFactory.class org.json.simple.parser.ContentHandler.class org.json.simple.parser.JSONParser.class org.json.simple.parser.ParseException.class org.json.simple.parser.Yylex.class org.json.simple.parser.Yytoken.class

JSON Object Encoding in Java: As we discussed above, this json.simple library is used to read/write or encode/decode JSON objects in Java. So let’s see how we can code for encoding part of the JSON object using JSONObject function. Now we create a java file mainEncoding.java and save the below-written code in it.

Java




import org.json.simple.JSONObject;
 
// Program for print data in JSON format.
public class JavaJsonEncoding {
    public static void main(String args[])
    {
        // In java JSONObject is used to create JSON object
        // which is a subclass of java.util.HashMap.
 
        JSONObject file = new JSONObject();
 
        file.put("Full Name", "Ritu Sharma");
        file.put("Roll No.", new Integer(1704310046));
        file.put("Tuition Fees", new Double(65400));
 
        // To print in JSON format.
        System.out.print(file);
    }
}
 
 

Output :

{"Full Name":"Ritu Sharma", "Roll No.":1704310046, "Tuition Fees":65400}

Now we will see how we can code for decoding part of the JSON object using JSONObjectfunction. Now we create a java file mainDecoding.java and save the below-written code in it. 

Java




import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
 
public class JavaJsonDecoding {
 
    public static void main(String[] args)
    {
        // Converting JSON data into Java String format
        String k = "{\"Full Name\":\"Ritu Sharma\", 
       \"Tuition Fees\":65400.0, \"Roll No.\":1704310046}";
        Object file = JSONValue.parse(k);
 
        // In java JSONObject is used to create JSON object
        JSONObject jsonObjectdecode = (JSONObject)file;
 
        // Converting into Java Data type
        // format From Json is the step of Decoding.
        String name
            = (String)jsonObjectdecode.get("Full Name");
        double fees
            = (Double)jsonObjectdecode.get("Tuition Fees");
        long rollno
            = (Long)jsonObjectdecode.get("Roll No.");
        System.out.println(name + " " + fees + " "
                           + rollno);
    }
}
 
 

Output :

Ritu Sharma 65400.0 1704310046

Note: Here Java JSON Encoding can also be done using a list or map. 



Next Article
How to parse JSON in Java

K

krishnakripa
Improve
Article Tags :
  • Java
  • JSON
Practice Tags :
  • Java

Similar Reads

  • Java Networking
    When computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
    15+ min read
  • How to Create JSON String in JavaScript?
    JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication. Below are the following approaches to creating a JSON string: Table of Conte
    2 min read
  • Working with JSON Files in R Programming
    JSON stands for JavaScript Object Notation. These files contain the data in human readable format, i.e. as text. Like any other file, one can read as well as write into the JSON files. In order to work with JSON files in R, one needs to install the "rjson" package. The most common tasks done using J
    4 min read
  • Network Input in Java
    In Java, Network Input is all about sending and getting data over a network. It's about making links, getting data from input sources, and dealing with the information we get. Java offers strong tools, like input streams and sockets. These help with these operations so communication between devices
    2 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
  • 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
  • How to Pretty Print JSON String in JavaScript?
    To pretty print JSON, you can format JSON strings with proper indentation, making them easy to read and debug. In JavaScript, you can achieve this using JSON.stringify() with optional parameters to specify the indentation level. Pretty printing JSON adds line breaks and spaces for readability.It is
    3 min read
  • How to Write JSON Array to CSV File using Java?
    We will see how to read a JSONArray from a JSON file and write the contents to a CSV file using Java. JavaScript Object Notation (JSON) is a standard text-based format for representing structured data that is based on JavaScript object syntax. It is commonly used for transmitting data in web applica
    3 min read
  • How to Master JSON in JavaScript?
    JSON is a text format for representing structured data, typically in the form of key-value pairs. It primarily sends data between a server and a client, especially in web APIs. Objects are enclosed in curly braces {} and contain key-value pairs.Arrays are enclosed in square brackets [] and hold valu
    5 min read
  • How to Convert JSON to string in JavaScript ?
    In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission. Several methods can be used
    3 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