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:
- Understanding JSON
- Setting Up the Environment
- Creating a JSON Object
- Populating a JSON Array
- Writing JSON Data to a File
- 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
Reference:
- https://github.com/fangyidong/json-simple