Parsing/Building JSON in Java

Example for building/parsing JSON in JAVA

A JSON Object can be created using Java very easily using any JSON library.
We are using JSON-Simple.jar to build/parse the JSON Object using Java.

Building JSON Object in JAVA:


					
import org.json.simple.JSONObject;

class JSONBuilder {

   public static void main(String[] args){
      JSONObject jsonObject = new JSONObject();

      jsonObject.put("names", "testjsonuser3");
      jsonObject.put("action", "IllustrateJSONObjectInScript");
      jsonObject.put("logincount", "3");
      
      System.out.print(jsonObject);
   }
}
					
					

Result:

{"names":"testjsonuser3","actions":"IllustrateJSONObjectInScript","logincount":3}

We could see the result displays the JSON Object., and it has string field printed with double quotes.
The java Object is created with only name value pairs in jsonObject field.

Parsing JSON Object in JAVA

						
import org.json.simple.JSONObject;

class JSONBuilder {

   public static void main(String[] args){
      JSONObject jsonObject = new JSONObject();

      jsonObject.put("names", "testjsonuser3");
      jsonObject.put("actions", "IllustrateJSONObjectInScript");
      jsonObject.put("logincount", "3");
      
      System.out.print(jsonObject);
	  
	  StringWriter out = new StringWriter();
	  jsonObject.writeJSONString(out);
      
	  String jsonString = out.toString();
	  System.out.println("JSON Converted to String:");
	  System.out.print(jsonString);
	  
	  System.out.println("JSONObject Values:");
	  System.out.print("names:" + jsonObject.get("names"));
  	  System.out.print(",actions:" + jsonObject.get("actions"));
  	  System.out.print(",logincount:" + jsonObject.get("logincount"));
   
   }
}
		
					

Result:

					
JSON Converted to String:						
{"names": "testjsonuser3", "actions":"IllustrateJSONObjectInScript", "logincount":3}						
JSONObject Values:
names:testjsonuser3,actions: IllustrateJSONObjectInScript,logincount: 3
					
					


In Java, JSON object can be directly converted to String and we can do String manipulations. Also, the JSON Object created can be parsed using the field name present in JSON Object.
The "names", "actions" and "logincount" values is displayed by parsing the object jsonObject directly in java as explained..



Reference  :  https://tutorialflow.com