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 Write to a File Using Applet?
Next article icon

How to Write JSON Array to CSV File using Java?

Last Updated : 14 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). This JSON in many scenarios is an array of objects, and thus, converting it to CSV makes it easily readable and comprehendible by people from all backgrounds. Let us take a deeper dive into how this can be achieved using Java. CDL (Comma Delimited List) Class from the package org.json is used here. This provides static methods to convert comma delimited text into a JSONArray and to convert a JSONArray into comma-delimited text.

Let us start by adding the following dependencies to our project:

A. The JSON library contains Java classes for parsing and converting between JSON and XML, HTTP headers, Cookies, Comma Delimited Lists, and Text, among other formats.

B. Apache Commons IO:  The FileUtils Class from Apache Commons IO is used to manipulate files which is moving, writing, and reading files.


<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>

Procedure: 

It is illustrated below step-by-step as shown below as follows: 

  1. Reading the JSON file and storing the result as a string.
  2. Construct a JSONObject using the above string.
  3. Fetch the JSON Array from the JSON Object.
  4. Create a new CSV file using java.io.File.
  5. Produce a comma delimited text from the JSONArray of JSONObjects and write it to the newly created CSV file.

Sample JSON file content

{
"test": [
{
"name": "Test User1",
"age": 22,
"role": "Developer"
},
{
"name": "Test User2",
"age": 40,
"role": "Analyst"
},
{
"name": "Test User3",
"age": 20,
"role": "Intern"
}
]
}

Implementation:

Input: In the current implementation there is no input needed. Make sure the path to the JSON file is correct.

Example

Java
// Java Program to Write Contents of JSONArray to a CSV File  // Importing required classes import java.io.*; import java.nio.file.*; import org.apache.commons.io.FileUtils; import org.json.*;  // Main class // To read JSON file and write the contents of // JSONArray to CSV file public class GFG {      // Main driver method     @SuppressWarnings("deprecation")     public static void main(String args[])     {         // Class data members         String jsonString;         JSONObject jsonObject;          // Try block to check for exceptions         try {              // Step 1: Reading the contents of the JSON file             // using readAllBytes() method and             // storing the result in a string             jsonString = new String(                 Files.readAllBytes(Paths.get("file.json")));              // Step 2: Construct a JSONObject using above             // string             jsonObject = new JSONObject(jsonString);              // Step 3: Fetching the JSON Array test             // from the JSON Object             JSONArray docs                 = jsonObject.getJSONArray("test");              // Step 4: Create a new CSV file using             //  the package java.io.File             File file = new File("C:\\Test.csv");              // Step 5: Produce a comma delimited text from             // the JSONArray of JSONObjects             // and write the string to the newly created CSV             // file              String csvString = CDL.toString(docs);             FileUtils.writeStringToFile(file, csvString);         }          // Catch block to handle exceptions         catch (Exception e) {              // Display exceptions on console with line             // number using printStackTrace() method             e.printStackTrace();         }     } } 

Sample Output: The contents of the Sample JSONArray are now correctly displayed in the file which is as displayed in the below image as follows:

Output Image



Next Article
How to Write to a File Using Applet?

B

bamrahprabhjyot
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • How to Write to a File Using Applet?
    In this article, we will learn how to write a file using Applet and grant access to write files using Applet. ApproachThe applet output window contains three fields. Those are the file name field, Text area field, and save button field. File name field: It asks the user to enter the file name to wri
    3 min read
  • Writing a CSV file in Java using OpenCSV
    A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently
    5 min read
  • Convert byte[] array to File using Java
    As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementatio
    3 min read
  • How to Write Data from HashMap to Excel using Java in Apache POI?
    Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with ex
    3 min read
  • How to Convert Vector to Array in Java?
    As we all know an array is a group of liked-typed variables that are referred to by a common name while on the other hand vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implement the List interface which gives a superior
    3 min read
  • Arrays.toString() in Java with Examples
    The Arrays.toString() method belongs to the Arrays class in Java. It converts an array into its string representation consisting of a list of the array's elements. In the case of an Object Array, if the array contains other arrays as elements, their string representation shows memory addresses inste
    3 min read
  • Program to convert Byte Array to Writer in Java
    References: Writer Class Approach: Writer class is used to write character stream, by which byte array can be passed as an argument. By this way, byte array can be converted into Writer class. To get the byte array from String, getBytes() method is used. Below is the implementation of the above appr
    2 min read
  • Reading a CSV file in Java using OpenCSV
    A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently th
    7 min read
  • Reading and Writing Data to Excel File in Java using Apache POI
    In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. Apache POI is an open-source java library designed for read
    5 min read
  • How to Create Pivot Table in Excel using Java?
    A pivot table is needed to quickly analyze data of a table with very little effort (and no formulas) and sometimes not everyone has time to look at the data in the table and see what’s going on and use it to build good-looking reports for large data sets in an Excel worksheet. Let's discuss a step-b
    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