Tuesday, May 29, 2018

How to Read Json file using Java

package com.guru99.readers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

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

public class JsonReader
{
   @SuppressWarnings("unchecked")
   public static void main(String[] args)
   {
       //JSON parser object to parse read file
       JSONParser jsonParser = new JSONParser();
       
       try {
       FileReader reader = new FileReader("pathof\\jsonData.json");
     
           //Read JSON file
           Object obj = jsonParser.parse(reader);

           JSONArray employeeList = (JSONArray) obj;
           System.out.println(employeeList);
           
           //Iterate over employee array
           employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );

       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } catch (ParseException e) {
           e.printStackTrace();
       }
   }

   private static void parseEmployeeObject(JSONObject employee)
   {
       //Get employee object within list
       JSONObject employeeObject = (JSONObject) employee.get("employee");
       
       //Get employee first name
       String firstName = (String) employeeObject.get("firstName"); 
       System.out.println(firstName);
       
       //Get employee last name
       String lastName = (String) employeeObject.get("lastName");
       System.out.println(lastName);
       
       //Get employee website name
       String website = (String) employeeObject.get("website"); 
       System.out.println(website);
   }
}

No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...