|
Processing JSON in Java
An Introduction |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
Json
JsonParser
JsonParser object's
next() methodSTART_ARRAY, END_ARRAY
START_OBJECT, END_OBJECT
KEY_NAME - the name in a name/value pairVALUE_STRING, VALUE_NUMBER,
VALUE_TRUE, VALUE_FALSE,
VALUE_NULL
getString(),
getObject(), getArray(),
getInt(), getBigDecimal()
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);
}
}
}
}
}
Json
JsonReader
JsonObjectBuilder
JsonArrayBuilder
JsonArray
JsonNumber
JsonObject
JsonString
JsonValue
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"));
}
}