package com.guru99.readers;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class WriteToJson
{
@SuppressWarnings("unchecked")
public static void main( String[] args )
{
//First Employee
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Ramesh");
employeeDetails.put("lastName", "Kudikala");
employeeDetails.put("website", "howtodoinjava.com");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
//Second Employee
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Raghu");
employeeDetails2.put("lastName", "Kunchey");
employeeDetails2.put("website", "example.com");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
//Add employees to list
JSONArray employeeList = new JSONArray();
employeeList.add(employeeObject);
employeeList.add(employeeObject2);
//Write JSON file
try (FileWriter file = new FileWriter("pathof\\jsonData.json")) {
file.write(employeeList.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
---------------------------------------------------
[{"employee":{"firstName":"Lokesh","lastName":"Gupta","website":"howtodoinjava.com"}},{"employee":{"firstName":"Brian","lastName":"Schultz","website":"example.com"}}]
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class WriteToJson
{
@SuppressWarnings("unchecked")
public static void main( String[] args )
{
//First Employee
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Ramesh");
employeeDetails.put("lastName", "Kudikala");
employeeDetails.put("website", "howtodoinjava.com");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
//Second Employee
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Raghu");
employeeDetails2.put("lastName", "Kunchey");
employeeDetails2.put("website", "example.com");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
//Add employees to list
JSONArray employeeList = new JSONArray();
employeeList.add(employeeObject);
employeeList.add(employeeObject2);
//Write JSON file
try (FileWriter file = new FileWriter("pathof\\jsonData.json")) {
file.write(employeeList.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
---------------------------------------------------
[{"employee":{"firstName":"Lokesh","lastName":"Gupta","website":"howtodoinjava.com"}},{"employee":{"firstName":"Brian","lastName":"Schultz","website":"example.com"}}]
No comments:
Post a Comment