JSON(Javascript Object Notation) is a lightweight format of data exchange and it is independent of language. It is easily read and interpreted by humans and machines. Hence nowadays, everywhere JSON is getting used for transmitting data. Let us see how to prepare JSON data by using JSON.org JSON API in java
- JSON.simple is a library in java is used that allows parsing/generating/transforming/querying JavaScript Object Notation, etc.,
- Necessary jar file: json-simple-1.1.jar. It has to be available in the classpath
- In Maven-driven projects it should be present in pom.xml as follows
<dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency>
We can store the items in the form of JSONObject or JSONArray. JSONArray is nothing but the collection of multiple JSON Objects. A sample JSON object can be viewed as follows
Let us see the ways how to create a JSON object
JsonEncodeExample.java
Java
// Importing JSON simple library import org.json.simple.JSONObject; // Creating a public class public class JsonEncodeExample { // Calling the main method public static void main(String[] args) { // Creating an object of JSON class JSONObject geekWriterObject = new JSONObject(); // Entering the values using the created object geekWriterObject.put( "geekWriterId" , new Integer( 100 )); geekWriterObject.put( "geekWritterName" , "GeekAuthor1" ); geekWriterObject.put( "status" , new Boolean( true )); geekWriterObject.put( "publishedArticlesIn" , "Java,Python" ); // Printing the values through the created object System.out.print(geekWriterObject); } } |
On running the above program we can see the output as
If we beautify this using the online JSON viewer, we will get the same output as appeared in the sample JSON
JsonDecodeExample.java
Java
// importing JSON simple libraries import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; // Creating a public class public class JsonDecodeExample { // calling the main method public static void main(String[] args) { // creating an object of JSONparser JSONParser jsonParser = new JSONParser(); // defining and assigning value to a string String sampleString = "[28,{\"38\":{\"48\":{\"58\":{\"68\":[78,{\"88\":98}]}}}}]" ; try { Object object = jsonParser.parse(sampleString); // creating a JSON array JSONArray array = (JSONArray)object; System.out.println( "The array's first element is" ); // always start the index by 0 System.out.println(array.get( 0 )); System.out.println( "The array's second element is" ); System.out.println(array.get( 1 )); System.out.println(); // creating a JSON object JSONObject jsonObject = (JSONObject)array.get( 1 ); System.out.println( "Value of \"38\"" ); System.out.println(jsonObject.get( "38" )); } catch (ParseException pr) { System.out.println( "The elements position is: " + pr.getPosition()); System.out.println(pr); } } } |
On running the above program, we get the output as follows
Let us see how the JSONObject and JSONArray can be written in an external file named “author.json” via
JSONWriteExample.java
Java
// importing java simple libraries and JSON libraries import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.LinkedHashMap; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class JSONWriteExample { public static void main(String[] args) throws FileNotFoundException { // Json object is created JSONObject jsonObject = new JSONObject(); // Adding data using the created object jsonObject.put( "firstName" , "Rachel" ); jsonObject.put( "lastName" , "Green" ); jsonObject.put( "age" , 30 ); jsonObject.put( "noOfPosts" , 100 ); jsonObject.put( "status" , "active" ); // LinkedHashMap is created for address data Map addressMap = new LinkedHashMap( 4 ); addressMap.put( "road" , "MG Road Cross cut Street" ); addressMap.put( "city" , "Bangalore" ); addressMap.put( "state" , "Karnataka" ); addressMap.put( "pinCode" , 560064 ); // adding address to the created JSON object jsonObject.put( "addressOfAuthor" , addressMap); // JSONArray is created to add the phone numbers JSONArray phoneNumberJsonArray = new JSONArray(); addressMap = new LinkedHashMap( 2 ); addressMap.put( "presentAt" , "home" ); addressMap.put( "phoneNumber" , "1234567890" ); // adding map to list phoneNumberJsonArray.add(addressMap); addressMap = new LinkedHashMap( 2 ); addressMap.put( "type2" , "fax1" ); addressMap.put( "no1" , "6366182095" ); // map is added to the list phoneNumberJsonArray.add(addressMap); // adding phone numbers to the created JSON object jsonObject.put( "phoneNos" , phoneNumberJsonArray); // the JSON data is written into the file PrintWriter printWriter = new PrintWriter( "author.json" ); printWriter.write(jsonObject.toJSONString()); printWriter.flush(); printWriter.close(); } } |
On running the above program, we can see the “author.json” file is created in the mentioned location and its contents are as follows (The output is beautified and shown here as reference)
Let us see how to read the JSON via
JSOnReadExample.java
Java
// importing JSON simple libraries import java.io.FileReader; import java.util.Iterator; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.*; public class JSONReadExample { public static void main(String[] args) throws Exception { // The file JSON.json is parsed Object object = new JSONParser().parse( new FileReader( "author.json" )); // objc is convereted to JSON object JSONObject jsonObject = (JSONObject)object; // obtaining the fname and lname String firstName = (String)jsonObject.get( "firstName" ); String lastName = (String)jsonObject.get( "lastName" ); System.out.println( "FirstName = " + firstName); System.out.println( "LastName = " + lastName); // age is obtained long ageOfAuthor = ( long )jsonObject.get( "age" ); System.out.println( "Age = " + ageOfAuthor); // address is obtained System.out.println( "Address details:" ); Map addressOfAuthor = ((Map)jsonObject.get( "addressOfAuthor" )); // iterating through the address Iterator<Map.Entry> iterator = addressOfAuthor.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry pair1 = iterator.next(); System.out.println(pair1.getKey() + " : " + pair1.getValue()); } // phone numbers are obtained System.out.println( "Phone Number details:" ); JSONArray phoneNumberJSONArray = (JSONArray)jsonObject.get( "phoneNos" ); // iterating phoneNumbers Iterator phoneNumberIterator = phoneNumberJSONArray.iterator(); while (phoneNumberIterator.hasNext()) { iterator = ((Map)phoneNumberIterator.next()) .entrySet() .iterator(); while (iterator.hasNext()) { Map.Entry pair1 = iterator.next(); System.out.println(pair1.getKey() + " : " + pair1.getValue()); } } } } |
On running the program, we can see the output as follows:
Conclusion
JSON is a lightweight easily readable, understandable, and iteratable transportation medium. Nowadays it is the output mechanism that got followed in any REST API calls. This way of mechanism is easily understood in android and IOS development and hence one JSON output of REST API call serves the purpose of many communications.