Tuesday, March 29, 2016

Java JSON Examples : How To Read JSON File Using JSON Simple

Intro


This examples will demonstrates how to read JSON file using JSON Simple. To read a JSON file, you can use JSONParser class to read each of the values.

Examples


package com.freesamplecode.java.json.simple;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class ReadJSONFileDemo {
 public static void main(String[] args){
  JSONParser jsonParser = new JSONParser();
  String fileName = "C:/TEMP/test.json";
  
  try {
   Object obj = jsonParser.parse(new FileReader(fileName));
   
   JSONObject jsonObject = (JSONObject) obj;
   
   String name = (String) jsonObject.get("name");
   String country = (String) jsonObject.get("country");
   
   System.out.println("Name : "+name);
   System.out.println("Country : "+country);
   System.out.print("Hobbies : ");
   
   JSONArray jsonArray = (JSONArray) jsonObject.get("hobbies");
   Iterator it = jsonArray.iterator();
   while(it.hasNext()){
    System.out.print(it.next()+", ");
   }
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ParseException e) {
   e.printStackTrace();
  }
  
 }
}

Output


Name : Nursalim
Country : Indonesia
Hobbies : Reading, Coding, Traveling, 

Screenshoot


How To Read JSON File Using JSON Simple In Java

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