Wednesday, March 9, 2016

Java JSON Example : How To Create A JSON File Using JSON Simple

Intro


JSON Simple is a java third party library for JSON processing for example to write a json file, to read a json file, and etc.

Please include the json-simple.jar library into your Java path to use it.

Example


package com.freesamplecode.java.json.simple;

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

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

public class CreateJSONFileDemo {
 public static void main(String[] args){
  
  // create an json object and put value into json object
  JSONObject jsonObject= new JSONObject();
  jsonObject.put("name", "Nursalim");
  jsonObject.put("country", "Indonesia");
  
  JSONArray hobbies = new JSONArray();
  hobbies.add("Reading");
  hobbies.add("Coding");
  hobbies.add("Traveling");
  
  jsonObject.put("hobbies", hobbies);
  
  try {
   
   //write json object into file
   
   FileWriter fw = new FileWriter("c:/temp/test.json");
   fw.write(jsonObject.toString());
   fw.flush();
   fw.close();
   
   System.out.println("File test.json is successfully created ");
  } catch (IOException e) {
   System.out.println("Failed to create a json file");
   e.printStackTrace();
  }
  
 }
}


Output


File test.json is successfully created 


Screenshot

How To Create A JSON File

Related Posts:

0 comments: