JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. Sample JSON document −
{ "book": [ { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "07", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ] }
Json-simple library
The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program.
JSON-Simple maven dependency
Following is the maven dependency for the JSON-simple library −
<dependencies> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> </dependencies>
Paste this with in the <dependencies> </dependencies> tag at the end of your pom.xml file. (before </project> tag)
Example
To create a JSON document using a Java program −
- Instantiate the JSONObject class of the json-simple library.
//Creating a JSONObject object JSONObject jsonObject = new JSONObject();
- Insert the required key-value pairs using the put() method of the JSONObject class.
jsonObject.put("key", "value");
- Write the created JSON object into a file using the FileWriter class as −
FileWriter file = new FileWriter("E:/output.json"); file.write(jsonObject.toJSONString()); file.close();
Following Java program creates a JSON object and writes it into a file named output.json.
Example
import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONObject; public class CreatingJSONDocument { public static void main(String args[]) { //Creating a JSONObject object JSONObject jsonObject = new JSONObject(); //Inserting key-value pairs into the json object jsonObject.put("ID", "1"); jsonObject.put("First_Name", "Shikhar"); jsonObject.put("Last_Name", "Dhawan"); jsonObject.put("Date_Of_Birth", "1981-12-05"); jsonObject.put("Place_Of_Birth", "Delhi"); jsonObject.put("Country", "India"); try { FileWriter file = new FileWriter("E:/output.json"); file.write(jsonObject.toJSONString()); file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("JSON file created: "+jsonObject); } }
Output
JSON file created: { "First_Name":"Shikhar", "Place_Of_Birth":"Delhi", "Last_Name":"Dhawan", "Country":"India", "ID":"1", "Date_Of_Birth": "1981-12-05"}
If you observe the contents of the JSON file you can see the created data as −