JMU
Processing JSON in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


The Java API for JSON Processing (JSON-P)
Element-Based Parsing
Element-Based Parsing (cont.)
Element-Based Parsing (cont.)
Element-Based Parsing (cont.)

An Example

javaexamples/jsonp/ElementBasedExample.java
        import java.io.*;
import javax.json.*;
import javax.json.stream.*;


/**
 * An example of element-based parsing using JSON-P.
 *
 * @author  Prof. David Bernstein, James Madison University
 */
public class ElementBasedExample
{
    /**
     * The entry point of the application.
     *
     * @param args  The command line arguments (which are ignored)
     */
    public static void main(String[] args) throws Exception
    {
        BufferedReader in = new BufferedReader(
            new FileReader(
                new File("../../jsonexamples/basics/person.json")));

        // Create the JsonParser
        JsonParser parser = Json.createParser(in);

        // Process events
        while (parser.hasNext())
        {
            JsonParser.Event evt = parser.next();
            if (evt == JsonParser.Event.KEY_NAME)
            {
                String name = parser.getString();
                if (name.equals("firstName"))
                {
                    // Move to the next state
                    parser.next();           

                    // Get the String for the value
                    String value = parser.getString();
                    System.out.println(value);
                }
            }
        }
    }
}
        
Document-Based Parsing
Document-Based Parsing (cont.)
Document-Based Parsing (cont.)

An Example

javaexamples/jsonp/DocumentBasedExample.java
        import java.io.*;
import javax.json.*;

/**
 * An example of document-based parsing using JSON-P.
 *
 * @author  Prof. David Bernstein, James Madison University
 */
public class DocumentBasedExample
{
    /**
     * The entry point of the application.
     *
     * @param args  The command line arguments (which are ignored)
     */
    public static void main(String[] args) throws Exception
    {
        BufferedReader in = new BufferedReader(
            new FileReader(
                new File("../../jsonexamples/basics/person.json")));

        // Create the JsonReader
        JsonReader reader = Json.createReader(in);

        // Use the JsonReader to read the JsonObject
        JsonObject person = reader.readObject();

        // Access a top-level attribute of the JsonObject
        System.out.println(person.getString("firstName"));

        // Move into the hierarchy
        JsonObject address = person.getJsonObject("address");        
        System.out.println(address.getString("city"));
    }
}