dcsimg
 

Creating a JSON Object in Java

Thursday Apr 22nd 2021 by Sridhar M S
Article Image

JSON is a standardized mechanism used to transfer & share data. Java supports this with the help of JSON libraries. Lets create a JSON Object in Java.

How to Create a JSON Object in Java

JSON is a standardized mechanism used to transfer and share data. Java supports this with the help of JSON related libraries. Below you will find an example of how to create an object in JSON and then print it out to a JSON file.

Code sample:

*/

import java.io.*; 
import java.util.*; 
import org.json.simple.JSONObject; 
  
public class CreateJSONObject 
{ 
    public static void main(String []args)   
    { 
		CreateJSONObject createJSONObject = new CreateJSONObject();
		createJSONObject.proceed();
	}
	
	private void proceed() throws FileNotFoundException
	{
        //Creating a JSONObject 
        JSONObject jsonObject = new JSONObject(); 
          
        //Updating data to the JSONObject
        jsonObject.put("firstName", "John"); 
        jsonObject.put("lastName", "Snow"); 
        jsonObject.put("dob", "25-Nov-1960"); 
          
        //Using LinkedHashMap to persist the address
        Map addressMap = new LinkedHashMap(4); 
        addressMap.put("street", "A104 9th Cross ABC Layout"); 
        addressMap.put("city", "Bangalore"); 
        addressMap.put("state", "KA"); 
        addressMap.put("pin", "560016"); 
          
        //Adding the addressMap to the JSONObject
        jsonObject.put("address", addressMap); 
          
        //Printing the contents of the JSONObject to a JSON file
        PrintWriter printWriter = new PrintWriter("OutputInJSONFormat.json"); 
        printWriter.write(jsonObject.toJSONString()); 
          
        printWriter.flush(); 
        printWriter.close(); 
		
		System.out.println("JSON file generated successfully.");
    } 
} 

/*

Output: $java CreateJSONObject JSON file generated successfully.

The file OutputInJSONFormat.json will have the following json data

{
    "firstName":"John",
    "lastName":"Snow",
    "address":{
        "street":"A104 9th Cross ABC Layout",
        "city":"Bangalore",
        "state":"KA",
        "pin":"560016"
    },
    "dob":"21-Nov-1960"
}

*/
Home
Mobile Site | Full Site