dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Apr 22, 2021

Creating 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"
}

*/
Sridhar M S
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date