BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Standard Java API for JSON

Standard Java API for JSON

Leia em Português

This item in japanese

Lire ce contenu en français

Bookmarks

JSR-353, the Java API for JSON Processing (JSON-P), has reached final approval ballot this month. JSON-P (similar to JAXP) consists of a Streaming API (similar to StAX) and an Object Model API (similar to DOM). The reference implementation is jsonp, currently in beta, and open sourced under CDDL v1.1 and GPL v2. JSON-P will be part of upcoming Java EE 7, and will be used by JAX-RS for its default JSON implementation. Please note that this API does not include JSON data binding (similar to JAXB), and is unrelated to the more popular JSONP or "JSON with padding".

JSON (JavaScript Object Notation) is a lightweight data-interchange format, and is used in web applications, REST services and NoSQL databases. With the popularity of JSON, and the arrival of many JSON libraries for the Java platform (org.json, Jackson, google-gson, etc), there is now a need to standardize how developers create and consume JSON. JSON-P is the upcoming standard, and can be used standalone, or as a part of Java EE 7 containers.

JSON-P is split into two APIs, the Streaming API (javax.json.stream), and the Object Model API (javax.json). The Streaming API is a low-level, efficient way to parse and generate JSON. It consists of two primary abstractions, JsonParser and JsonGenerator. JsonParser is a pull parser that allows forward, read-only access to a JSON input source. JsonGenerator provides methods to write JSON to a stream, and allows for method chaining. The generator writes name/value pairs in JSON objects and values in JSON arrays.

Here are code samples of JsonParser and JsonGenerator. First is the JSON data we will be reading or creating.

[
  {
    "type" : "home",
    "number" : "(800) 111-1111"
  },
  {
    "type" : "cell",
    "number" : "(800) 222-2222"
  }
]

Here we have our JsonParser example, with its output at the bottom.

JsonParserFactory factory = Json.createParserFactory(null);
JsonParser parser = factory.createParser(new StringReader(json));

while (parser.hasNext()) {
  Event event = parser.next();

  switch (event) {
    case KEY_NAME: {
      System.out.print(parser.getString() + "="); break;
    }
    case VALUE_STRING: {
      System.out.println(parser.getString()); break;
    }
  }
}

type=home
number=(800) 111-1111
type=cell
number=(800) 222-2222

Here we have our JsonGenerator example, which prints JSON to System.out.

JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
JsonGenerator generator = factory.createGenerator(System.out);

generator.writeStartArray().
  writeStartObject().
    write("type", "home").
    write("number", "(800) 111-1111").writeEnd().
  writeStartObject().
    write("type", "cell").
    write("number", "(800) 222-2222").writeEnd().
  writeEnd().close();

Next is the Object Model API, which is a simple, easy to use, high level API, implemented on top of the Streaming API. It creates a tree-like structure that represents the JSON data in memory, which can be easily navigated and queried. The primary abstractions in the Object Model API are JsonObject and JsonArray, both of which are immutable. JsonObject provides a Map view to access the unordered collection of name/value pairs from the model. JsonArray provides a List view to access the ordered sequence of values. To create these object models, you can use the builder pattern (JsonObjectBuilder and JsonArrayBuilder) or read them from an input source (InputStream or Reader) using JsonReader. You can then write these object models to an output source (OutputStream or Writer) using the JsonWriter.

Here is an example of creating JsonArray using JsonArrayBuilder. Again, we are working with the JSON data above.

JsonBuilderFactory factory = Json.createBuilderFactory(null);
JsonArray jsonArray = factory.createArrayBuilder()
    .add(factory.createObjectBuilder().
        add("type", "home").
        add("number", "(800) 111-1111"))
    .add(factory.createObjectBuilder().
        add("type", "cell").
        add("number", "(800) 222-2222")).build();

Here is the example for JsonReader.

try (JsonReader jsonReader = Json.createReader(new StringReader(json))) {
  JsonArray array = jsonReader.readArray();
  System.out.println(array);
}

Here is the example for JsonWriter.

try (JsonWriter jsonWriter = Json.createWriter(System.out)) {
  jsonWriter.writeArray(jsonArray);
}

To try out the beta release, you can download jsonp, or use the javax.json:javax.json-api:1.0-b06 and org.glassfish:javax.json:1.0-b06 Maven artifacts. You will need Java SE 6 or higher. For more information, visit the official Java API for JSON Processing website, and read the JSON Processing Javadocs. You might also want to watch the Java API for JSON Processing presentation from JavaOne on YouTube.

Rate this Article

Adoption
Style

BT