Parsing JSON in Java: An Introduction

JSON, or JavaScript Object Notation, is a commonly used format for storing and transferring data, especially in mobile apps and web programming. The data is stored in a simple text format, and can store nearly anything, including arrays and objects as just a collection of plain text. Because it is just plain text, it is compact and quick to send and can be easily read by almost every programming language out there, including Java.

Parsing JSON in Java: An Introduction

JSON is most commonly used with Ajax (Asynchronous JavaScript And XML) and RESTful data exchange systems. Nearly every website now uses JSON with RESTful.

A JSON object is a collection of unordered name/value pairs. This collection can hold any number of pairings, including none at all. A JSON array is a series of values, much like a simple string of characters. The values, however, can be Boolean, Null, Numbers, Strings, or even more arrays and objects.

Writing a basic JSON string is very easy and follows a set of standard rules:

  1. JSON strings must contain either an array or an object, as noted above.
  2. An array is contained within brackets ([, ]) and includes a set of CSV (comma-separated values).
  3. An object is contained within curly braces ({, }) and includes a set of comma-separated name/value pairs.
  4. A name/value pair is written like so: “field name”: field value.
  5. JSON values can be of the following types:
    • Array
    • Boolean
    • null
    • integer or floating-point number
    • Object
    • String (in double quotes)

As an example, this is how you might store customer information in JSON format:

{
  "firstName": "Adam",
  "lastName": "Smith",
  "customerID": 1234,
  "address": {
    "street": "123 Anywhere Dr.",
    "city": "New York",
    "state": "NY",
    "zip": "10012"
  }
}

The entire string is noted as an object because of the curly braces, and inside, the name/value pairs are easily identifiable. The address name is paired with an object that contains the entire street address broken down into distinct name/value pairs as well.

So let’s look at how to parse this and work with it in Java using Java’s API for JSON processing.

Step-by-Step Guide to Parsing JSON in Java

JSON.simple is a lightweight and simple Java library that lets you work with JSON as needed. You can generate, parse, query, and transform JSON strings easily. Download the json-simple-1.1 jar and put it in your CLASSPATH to enable the functionality. The documentation for the toolkit can be found here.

Writing Data to a JSON String

So first, let’s write the above customer data to a JSON string. The first step is to import the java.io and java.util libraries to enable maps and input/output streams. You also need to import the JSONObject from json.simple. We won’t be importing the JSONArray because our example does not have an array, but the process is identical to writing to an object.

Here is the code snippet:

// Java snippet to write a JSON example to a file 
 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.LinkedHashMap; 
import java.util.Map; 
import org.json.simple.JSONObject; 
 
public class WriteExampleJSON 
{ 
  public static void main(String[] args) throws FileNotFoundException 
  { 
    // create a new JSONObject 
    JSONObject JSONExample = new JSONObject(); 
    
    JSONExample.put("firstName", "Adam"); 
    JSONExample.put("lastName", "Smith");
    JSONExample.put("customerID", 1234);     
    
    // for the address, first create a LinkedHashMap 
    Map JSONAddress = new LinkedHashMap(4); 
    JSONAddress.put("street", "123 Anywhere Dr."); 
    JSONAddress.put("city", "New York"); 
    JSONAddress.put("state", "NY"); 
    JSONAddress.put("zip", 10012); 
    
    // putting address to JSONObject 
    JSONExample.put("address", JSONAddress); 
    
    // write JSON to external file:"JSONExample.json" 
    PrintWriter pw = new PrintWriter("JSONExample.json"); 
    pw.write(jo.toJSONString()); 
    
    pw.flush(); 
    pw.close(); 
  } 
} 

This will create a file that looks like the initial example.

Reading and Parsing a JSON Data String

If you are pulling a JSON string from somewhere, you’ll need to be able to parse that out into usable content. When you pull a JSON string, you will need to know the contents of the string to parse it into useful content. If you don’t know the contents, then you can potentially parse a JSON data string into readable content by using a delimiter and the Split String command, but that’s for another tutorial. In this case, we know what the data string contains.

// sample code to parse a known JSON data string 
 
import java.io.*; 
import java.util.*;  
 
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.*; 
 
public class ReadExampleJSON 
{ 
  public static void main(String[] args) throws Exception 
  { 
    // parsing file "JSONExample.json" 
    Object JSONParse = new JSONParser().parse(new FileReader("JSONExample.json")); 
    
    // typecasting obj to JSONObject 
    JSONObject newJSONObject = (JSONObject) JSONParse; 
    
    // parsing first and last names 
    String firstName = (String) newJSONObject.get("firstName"); 
    String lastName = (String) newJSONObject.get("lastName"); 
    
    System.out.println("First Name: " + firstName);
    System.out.println("Last Name: " + lastName);
    
    // parsing customerID
    int customerID = (int) newJSONObject.get("customerID"); 
    System.out.println("Customer ID: " + customerID);
   
    // parse customer address
    Map address = ((Map)newJSONObject.get("address")); 
    
    // iterating address as a Map and printing it out
    Iterator<Map.Entry> iterator1 = address.entrySet().iterator(); 
    while (iterator1.hasNext()) { 
      Map.Entry pair = iterator1.next(); 
      System.out.println(pair.getKey() + " : " + pair.getValue()); 
    }  
  } 
}

The output then looks like this:

First Name: Adam
Last Name: Smith
Customer ID: 1234
street : 123 Anywhere Dr.
city : New York
state : NY
zip : 10012

It is important to note that when dealing with JSON objects, the name/value pairs are unordered. This means that the order is insignificant, so when written to the output file, the address name/value pairs can be out of the original order. If you need to arrange the data in a specific order when you parse it, you can use the map.get(key) function to get the specific values you need after you’ve iterated through the entire String.

Conclusion

JSON is an extremely valuable type of notation that allows for the quick and lightweight transfer of essential information from databases or other data-centric locations to mobile and desktop applications. By understanding how to write a JSON data string and parse information from it, you can see how efficient sending even thousands of data strings can be. This is only the first step in all that JSON has to offer to those interested in Java development on both mobile and web applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top