- Forward


Processing JSON in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

The Java API for JSON Processing (JSON-P)
Back SMYC Forward
  • Purpose:
    • Parse, generate, transform and query JSON documents
  • It Supports:
    • Element-Based Parsing
    • Document-Based Parsing
  • A Popular Alternative:
    • Jackson
Element-Based Parsing
Back SMYC Forward
  • Approach:
    • Process each element in the source JSON document individually (in a "streaming" fashion)
    • Ignore the hierarchical nature of the JSON document
  • Rationale:
    • Very convenient when the hierarchical structure is not important
Element-Based Parsing (cont.)
Back SMYC Forward
  • Important Classes in the "Streaming" API:
    • Json
    • JsonParser
  • Events:
    • Are returned by the JsonParser object's next() method
Element-Based Parsing (cont.)
Back SMYC Forward
  • Events:
    • START_ARRAY, END_ARRAY
    • START_OBJECT, END_OBJECT
    • KEY_NAME - the name in a name/value pair
    • VALUE_STRING, VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, VALUE_NULL
  • Getters:
    • Must be called when the parser is in the appropriate state
    • One for each element (i.e., getString(), getObject(), getArray(), getInt(), getBigDecimal()
Element-Based Parsing (cont.)
Back SMYC Forward

An Example

javaexamples/jsonp/ElementBasedExample.java
 
Document-Based Parsing
Back SMYC Forward
  • Approach:
    • Constructs a tree of objects from the JSON document
  • Providing Access to the Tree:
    • Use an element of the tree
Document-Based Parsing (cont.)
Back SMYC Forward
  • Important Classes in the "Object Model" API:
    • Json
    • JsonReader
    • JsonObjectBuilder
    • JsonArrayBuilder
  • The Objects:
    • JsonArray
    • JsonNumber
    • JsonObject
    • JsonString
    • JsonValue
Document-Based Parsing (cont.)
Back SMYC Forward

An Example

javaexamples/jsonp/DocumentBasedExample.java
 
There's Always More to Learn
Back -