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:
1 2 3 4 5 |
<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:
1 2 3 4 5 6 7 8 9 |
{ "Name": "crunchify.com", "Author": "App Shah", "Company List": [ "Compnay: eBay", "Compnay: Paypal", "Compnay: Google" ] } |
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.crunchify.tutorials; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * @author Crunchify.com */ public class CrunchifyJSONFileWrite { @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { JSONObject obj = new JSONObject(); obj.put("Name", "crunchify.com"); obj.put("Author", "App Shah"); JSONArray company = new JSONArray(); company.add("Compnay: eBay"); company.add("Compnay: Paypal"); company.add("Compnay: Google"); obj.put("Company List", company); // try-with-resources statement based on post comment below :) try (FileWriter file = new FileWriter("/Users/<username>/Documents/file1.txt")) { file.write(obj.toJSONString()); System.out.println("Successfully Copied JSON Object to File..."); System.out.println("\nJSON Object: " + obj); } } } |
In above example FileWriter
instance is declared in a try-with-resource
statement, it will be closed regardless of whether the try statement completes normally or abruptly. You don’t have catch IOException
or no need to mention finally
block.
Compare above code with below with try, catch, finally code. Above code is just 4 lines compare to 11 lines below.
Output:
1 2 3 |
Successfully Copied JSON Object to File... JSON Object: {"Name":"crunchify.com","Author":"App Shah","Company List":["Compnay: eBay","Compnay: Paypal","Compnay: Google"]} |
Reference:
https://github.com/fangyidong/json-simple
Download JSON.simple from here.