How to write JSON object to File in Java? Simplifying JSON File Handling in Java

Last updated
App Shah
Crunchify » JSON Tutorials » How to write JSON object to File in Java? Simplifying JSON File Handling in Java

Simplifying JSON File Handling in Java: A Step-by-Step Guide with Logging.

Simplifying JSON File Handling in Java - A Step-by-Step Guide with Logging

In this tutorial, I’ll show you how to write JSON data to a file using JSON.simple .

JSON.simple is a simple Java toolkit for JSON. You can use JSON.simple to encode or decode JSON text.

Maven Dependency:

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

Features:

  • Full compliance with JSON specification (RFC4627) and reliable (see compliance testing)
  • Provides multiple functionalities such as encode, decode/parse and escape JSON text while keeping the library lightweight
  • Flexible, simple and easy to use by reusing Map and List interfaces
  • Supports streaming output of JSON text
  • Stoppable SAX-like interface for streaming input of JSON text (learn more)
  • Heap based parser
  • High performance (see performance testing)
  • No dependency on external libraries
  • Both of the source code and the binary are JDK1.2 compatible

Here is a file1.txt content:

{
    "Name": "crunchify.com",
    "Author": "App Shah",
    "Company List": [
        "Compnay: eBay",
        "Compnay: Paypal",
        "Compnay: Google"
    ]
}

In the realm of modern software development, handling data interchange formats like JSON (JavaScript Object Notation) is a common task. Java, being a versatile and widely used programming language, provides libraries and tools that make working with JSON a breeze.

In this blog post, we’ll dive into a practical example that demonstrates how to create, manipulate, and write JSON data to a file in Java. Additionally, we’ll enhance the program with basic logging to keep track of our progress.

Table of Contents:

  1. Understanding JSON
  2. Setting Up the Environment
  3. Creating a JSON Object
  4. Populating a JSON Array
  5. Writing JSON Data to a File
  6. Enhancing with Logging

Java Code:

package crunchify.com.tutorials;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author crunchify.com
 * Simplifying JSON File Handling in Java: A Step-by-Step Guide with Logging
 */

public class CrunchifyJSONFileWrite {
    private static FileWriter crunchifyFile;

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {

        try {
            // JSON object.
            // Key value pairs are unordered.
            // JSONObject supports java.util.Map interface.
            JSONObject crunchifyObj = new JSONObject();
            crunchifyObj.put("Name", "crunchify.com");
            crunchifyObj.put("Author", "App Shah");

            JSONArray crunchifyCompany = new JSONArray();
            crunchifyCompany.add("Company: Facebook");
            crunchifyCompany.add("Company: PayPal");
            crunchifyCompany.add("Company: Google");
            crunchifyObj.put("Company List", crunchifyCompany);

            // Constructs a FileWriter given a file name, using the platform's default charset
            crunchifyFile = new FileWriter("/Users/Shared/crunchify.txt");
            crunchifyFile.write(crunchifyObj.toJSONString());

            crunchifyLog("Successfully Copied JSON Object to File...");
            crunchifyLog("\nJSON Object: " + crunchifyObj);

            crunchifyFile.flush();
            crunchifyFile.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static public void crunchifyLog(String str) {
        System.out.println(str);
    }
}

Let’s go over details:

1. Understanding JSON:

JSON, short for JavaScript Object Notation, is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It consists of key-value pairs and arrays, making it an ideal choice for representing structured data.

2. Setting Up the Environment:

Before we dive into the code, make sure you have a Java development environment set up. You’ll also need the json-simple library, which provides a straightforward way to work with JSON data. You can include the library in your project through your preferred build tool or by manually adding the JAR file.

3. Creating a JSON Object:

Our goal is to create a JSON object representing some basic information. Let’s create an instance of JSONObject and populate it with key-value pairs:

JSONObject obj = new JSONObject();
obj.put("Name", "crunchify.com");
obj.put("Author", "App Shah");

In this example, we’ve added the website’s name and the author’s name to the JSON object.

4. Populating a JSON Array:

Now, let’s enhance our JSON object by adding a list of companies. We’ll use a JSONArray to hold these companies:

JSONArray company = new JSONArray();
company.add("Company: Facebook");
company.add("Company: PayPal");
company.add("Company: Google");
obj.put("Company List", company);

Here, we’ve created a JSON array named company and added three company names to it. Then, we added the array to our existing JSON object under the key “Company List.”

5. Writing JSON Data to a File:

To persist our JSON data, we’ll create a file and write the JSON content to it:

try {
    FileWriter file = new FileWriter("/Users/Shared/crunchify.txt");
    file.write(obj.toJSONString());
    file.flush();
    file.close();
} catch (IOException e) {
    e.printStackTrace();
}

In this section, we’ve covered the basics of creating JSON data and writing it to a file. But what if we want to keep track of our progress and log important information during this process?

6. Enhancing with Logging:

Logging is a critical aspect of software development, allowing us to track events and troubleshoot issues. While there are dedicated logging libraries for Java, we’ll start with a simple logging method:

static public void crunchifyLog(String str) {
    System.out.println(str);
}

By adding this method, we can log messages to the console, which will help us understand what’s happening at different stages of our program.

Eclipse Console Output:

Successfully Copied JSON Object to File...

JSON Object: {"Author":"App Shah","Name":"crunchify.com","Company List":["Company: Facebook","Company: PayPal","Company: Google"]}

Process finished with exit code 0

How to write JSON object to File in Java? - IntelliJ IDEA Result

Reference:

16 thoughts on “How to write JSON object to File in Java? Simplifying JSON File Handling in Java”

  1. I am trying to write from mysql a json file. I do not know what is wrong with my code. When I write
    http://localhost:8085/Json3/testjson.jsp the information apprears as follows:

    [{“Nombre”:”Nancy”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Andrew”,”Cargo”:”Vice President, Sales”,”Empresa”:”Northwind Traders”},{“Nombre”:”Jan”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Mariya”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Steven”,”Cargo”:”Sales Manager”,”Empresa”:”Northwind Traders”},{“Nombre”:”Michael”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Robert”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Laura”,”Cargo”:”Sales Coordinator”,”Empresa”:”Northwind Traders”},{“Nombre”:”Anne”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Alex”,”Cargo”:”ing.”,”Empresa”:”acme”}]

    But I need to write this information json in a .json file. Before I creted a blank file “nuevo.json” and is located as follows: (Netbeans)
    Json3
    webpages
    index.html
    nuevo.json
    testjson.jsp

    testjson.jsp contains the following:

    When I see the “nuevo.json” is empty……….

    Reply
  2. Hi, I am trying to write from mysql a json file. I do not know what is wrong with my code. When I write
    http://localhost:8085/Json3/testjson.jsp the information apprears on the screen as follows:
    The connection is working because this is the infomation from the table

    [{"Nombre":"Nancy","Cargo":"Sales Representative","Empresa":"Northwind Traders"},{"Nombre":"Andrew","Cargo":"Vice President, Sales","Empresa":"Northwind Traders"},{"Nombre":"Jan","Cargo":"Sales Representative","Empresa":"Northwind Traders"},{"Nombre":"Mariya","Cargo":"Sales Representative","Empresa":"Northwind Traders"},{"Nombre":"Steven","Cargo":"Sales Manager","Empresa":"Northwind Traders"},{"Nombre":"Michael","Cargo":"Sales Representative","Empresa":"Northwind Traders"},{"Nombre":"Robert","Cargo":"Sales Representative","Empresa":"Northwind Traders"},{"Nombre":"Laura","Cargo":"Sales Coordinator","Empresa":"Northwind Traders"},{"Nombre":"Anne","Cargo":"Sales Representative","Empresa":"Northwind Traders"},{"Nombre":"Alex","Cargo":"ing.","Empresa":"acme"}]
    
    But I need to write this information json in a .json file. Before I creted a blank file "nuevo.json" and is located as follows: (Netbeans)
    
    Json3 (project name)
    webpages
     index.html
     nuevo.json
     testjson.jsp
    
    testjson.jsp contains the following:

    When I see the “nuevo.json” is empty……….

    Reply
  3. looks great. Btw you can use the builder design pattern in the JSON
    methods, it will be easier instead of rewriting .put all the time

    Reply
    • Hi Yoshi – good point. Thanks for sharing. I’ll give it a try may be next week..

      Keep your feedback coming.

      Reply
  4. Uhm.. try with resources does not automatically handle IOException, the only reason why you don’t have a catch in your try, is because you’re throwing IOException in your method signature..

    Reply
  5. try-with-resources;

    try (FileWriter file = new FileWriter("/Users//Documents/file1.txt")) {
    ...
    } catch(IOException exc) {
    ...
    }

    makes it so you don’t need the finally bit of the try-catch. I believe you have to have JDK 7+ however

    Anyway, thanks for sharing this, helped me do exactly what i wanted to.

    Reply
    • Hi there – I agree. Just updated above tutorial and added file1.txt content.

      {
          "Name": "crunchify.com",
          "Author": "App Shah",
          "Company List": [
              "Compnay: eBay",
              "Compnay: Paypal",
              "Compnay: Google"
          ]
      }
      Reply

Leave a Comment