Open In App

How to parse JSON in Java

Last Updated : 07 Aug, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.

Below is a simple example from Wikipedia that shows JSON representation of an object that describes a person. The object has string values for first name and last name, a number value for age, an object value representing the person’s address, and an array value of phone number objects.

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567" 
        }
    ] 
}

JSON Processing in Java : The Java API for JSON Processing JSON.simple is a simple Java library that allow parse, generate, transform, and query JSON.

Getting Started : You need to download the json-simple-1.1 jar and put it in your CLASSPATH before compiling and running the below example codes.

Json-Simple API : It provides object models for JSON object and array structures. These JSON structures are represented as object models using types JSONObject and JSONArray. JSONObject provides a Map view to access the unordered collection of zero or more name/value pairs from the model. Similarly, JSONArray provides a List view to access the ordered sequence of zero or more values from the model.

Write JSON to a file

Let us see an example that writes above JSON data into a file “JSONExample.json”, with help of JSONObject and JSONArray.




// Java program for write JSON to a file
  
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 
    {
        // creating JSONObject
        JSONObject jo = new JSONObject();
          
        // putting data to JSONObject
        jo.put("firstName", "John");
        jo.put("lastName", "Smith");
        jo.put("age", 25);
          
        // for address data, first create LinkedHashMap
        Map m = new LinkedHashMap(4);
        m.put("streetAddress", "21 2nd Street");
        m.put("city", "New York");
        m.put("state", "NY");
        m.put("postalCode", 10021);
          
        // putting address to JSONObject
        jo.put("address", m);
          
        // for phone numbers, first create JSONArray 
        JSONArray ja = new JSONArray();
          
        m = new LinkedHashMap(2);
        m.put("type", "home");
        m.put("number", "212 555-1234");
          
        // adding map to list
        ja.add(m);
          
        m = new LinkedHashMap(2);
        m.put("type", "fax");
        m.put("number", "212 555-1234");
          
        // adding map to list
        ja.add(m);
          
        // putting phoneNumbers to JSONObject
        jo.put("phoneNumbers", ja);
          
        // writing JSON to file:"JSONExample.json" in cwd
        PrintWriter pw = new PrintWriter("JSONExample.json");
        pw.write(jo.toJSONString());
          
        pw.flush();
        pw.close();
    }
}


Output from file “JSONExample.json” :

{
     "lastName":"Smith",
    "address":{
        "streetAddress":"21 2nd Street",
         "city":"New York",
         "state":"NY",
         "postalCode":10021
    },
     "age":25,
     "phoneNumbers":[
            {
            "type":"home", "number":"212 555-1234"
            },
         {
            "type":"fax", "number":"212 555-1234"
         }
     ],
     "firstName":"John"
}

Note : In JSON, An object is an unordered set of name/value pairs, so JSONObject doesn’t preserve the order of an object’s name/value pairs, since it is (by definition) not significant. Hence in our output file, order is not preserved.

Read JSON from a file

Let us see an example that read JSON data from above created file “JSONExample.json” with help of JSONParser, JSONObject and JSONArray.




// Java program to read JSON from a file
  
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 
    {
        // parsing file "JSONExample.json"
        Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
          
        // typecasting obj to JSONObject
        JSONObject jo = (JSONObject) obj;
          
        // getting firstName and lastName
        String firstName = (String) jo.get("firstName");
        String lastName = (String) jo.get("lastName");
          
        System.out.println(firstName);
        System.out.println(lastName);
          
        // getting age
        long age = (long) jo.get("age");
        System.out.println(age);
          
        // getting address
        Map address = ((Map)jo.get("address"));
          
        // iterating address Map
        Iterator<Map.Entry> itr1 = address.entrySet().iterator();
        while (itr1.hasNext()) {
            Map.Entry pair = itr1.next();
            System.out.println(pair.getKey() + " : " + pair.getValue());
        }
          
        // getting phoneNumbers
        JSONArray ja = (JSONArray) jo.get("phoneNumbers");
          
        // iterating phoneNumbers
        Iterator itr2 = ja.iterator();
          
        while (itr2.hasNext()) 
        {
            itr1 = ((Map) itr2.next()).entrySet().iterator();
            while (itr1.hasNext()) {
                Map.Entry pair = itr1.next();
                System.out.println(pair.getKey() + " : " + pair.getValue());
            }
        }
    }
}


Output:

John
Smith
25
streetAddress : 21 2nd Street
postalCode : 10021
state : NY
city : New York
number : 212 555-1234
type : home
number : 212 555-1234
type : fax


Similar Reads

getopt() function in C to parse command line arguments
The getopt() function is a builtin function in C and is used to parse command line arguments. Syntax: getopt(int argc, char *const argv[], const char *optstring) optstring is simply a list of characters, each representing a single character option. Return Value: The getopt() function returns different values: If the option takes a value, that value
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
31 min read
Java.net.Authenticator class in Java
Authenticator class is used in those cases where an authentication is required to visit some URL. Once it is known that authentication is required, it prompts the user for the same or uses some hard-coded username and password. To use this class, following steps are followed- Create a class that extends the Authenticator. Lets name it customAuth.Ov
3 min read
Java.util.Objects class in Java
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. Using Objects class methods, one can smartly handle NullPointerException and can also show customize
8 min read
Java lang.Long.builtcount() method in Java with Examples
java.lang.Long.bitCount() is a built in function in Java that returns the number of set bits in a binary representation of a number. It accepts a single mandatory parameter number whose number of set bits is returned. Syntax: public static long bitCount(long num) Parameters: num - the number passed Returns: the number of set bits in the binary repr
3 min read
Java.lang.Short toString() method in Java with Examples
toString(short) The static toString() method of java.lang.Short returns a new String object representing the specified short. The radix is assumed to be 10.This is a static method hence no object of Short class is required for calling this method. Syntax: public static String toString(short b) Parameters: This method accepts a parameter b which is
2 min read
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide
7 min read
Java.util.zip.DeflaterOutputStream class in Java
Java.util.zip.DeflaterInputStream class in Java This class implements an output stream filter for compressing data in the "deflate" compression format. It is also used as the basis for other types of compression filters, such as GZIPOutputStream. Constructors and Description DeflaterOutputStream(OutputStream out) : Creates a new output stream with
3 min read
Java.io.ObjectOutputStream Class in Java | Set 2
Java.io.ObjectOutputStream Class in Java | Set 1 More Methods: void write(byte[] buf) : Writes an array of bytes. This method will block until the byte is actually written. Syntax :public void write(byte[] buf) throws IOException Parameters: buf - the data to be written Throws: IOException void write(byte[] buf, int off, int len) : Writes a sub arr
8 min read
Java.lang.Boolean Class in Java
Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean. In addition, this class provides useful methods like to convert a boolean to a String and a String to a boolean, while dealing with a boolea
8 min read
Article Tags :
Practice Tags :