Java Platform, Enterprise Edition (Java EE) 8
The Java EE Tutorial

Previous Next Contents

Using the Object Model API

This section describes four use cases of the object model API: creating an object model from JSON data, creating an object model from application code, navigating an object model, and writing an object model to a stream.

The following topics are addressed here:

Creating an Object Model from JSON Data

The following code demonstrates how to create an object model from JSON data in a text file:

import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonStructure;
JsonReader reader = Json.createReader(new FileReader("jsondata.txt"));
JsonStructure jsonst =;

The object reference jsonst can be either of type JsonObject or of type JsonArray, depending on the contents of the file. JsonObject and JsonArray are subtypes of JsonStructure. This reference represents the top of the tree and can be used to navigate the tree or to write it to a stream as JSON data.

Creating an Object Model from Application Code

The following code demonstrates how to create an object model from application code:

import javax.json.Json;
import javax.json.JsonObject;
JsonObject model = Json.createObjectBuilder()
   .add("firstName", "Duke")
   .add("lastName", "Java")
   .add("age", 18)
   .add("streetAddress", "100 Internet Dr")
   .add("city", "JavaTown")
   .add("state", "JA")
   .add("postalCode", "12345")
   .add("phoneNumbers", Json.createArrayBuilder()
         .add("type", "mobile")
         .add("number", "111-111-1111"))
         .add("type", "home")
         .add("number", "222-222-2222")))

The object reference model represents the top of the tree, which is created by nesting calls to the add methods and built by calling the build method. The JsonObjectBuilder class contains the following add methods:

JsonObjectBuilder add(String name, BigDecimal value)
JsonObjectBuilder add(String name, BigInteger value)
JsonObjectBuilder add(String name, boolean value)
JsonObjectBuilder add(String name, double value)
JsonObjectBuilder add(String name, int value)
JsonObjectBuilder add(String name, JsonArrayBuilder builder)
JsonObjectBuilder add(String name, JsonObjectBuilder builder)
JsonObjectBuilder add(String name, JsonValue value)
JsonObjectBuilder add(String name, long value)
JsonObjectBuilder add(String name, String value)
JsonObjectBuilder addNull(String name)

The JsonArrayBuilder class contains similar add methods that do not have a name (key) parameter. You can nest arrays and objects by passing a new JsonArrayBuilder object or a new JsonObjectBuilder object to the corresponding add method, as shown in this example.

The resulting tree represents the JSON data from JSON Syntax.

The following code demonstrates a simple approach to navigating an object model:

import javax.json.JsonValue;
import javax.json.JsonObject;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonString;
public static void navigateTree(JsonValue tree, String key) {
   if (key != null)
      System.out.print("Key " + key + ": ");
   switch(tree.getValueType()) {
      case OBJECT:
         JsonObject object = (JsonObject) tree;
         for (String name : object.keySet())
            navigateTree(object.get(name), name);
      case ARRAY:
         JsonArray array = (JsonArray) tree;
         for (JsonValue val : array)
            navigateTree(val, null);
      case STRING:
         JsonString st = (JsonString) tree;
         System.out.println("STRING " + st.getString());
      case NUMBER:
         JsonNumber num = (JsonNumber) tree;
         System.out.println("NUMBER " + num.toString());
      case TRUE:
      case FALSE:
      case NULL:

The method navigateTree can be used with the models built in Creating an Object Model from JSON Data and Creating an Object Model from Application Code as follows:

navigateTree(model, null);

The navigateTree method takes two arguments: a JSON element and a key. The key is used only to help print the key-value pairs inside objects. Elements in a tree are represented by the JsonValue type. If the element is an object or an array, a new call to this method is made for every element contained in the object or array. If the element is a value, it is printed to the standard output.

The JsonValue.getValueType method identifies the element as an object, an array, or a value. For objects, the JsonObject.keySet method returns a set of strings that contains the keys in the object, and the JsonObject.get(String name) method returns the value of the element whose key is name. For arrays, JsonArray implements the List<JsonValue> interface. You can use enhanced for loops with the Set<String> instance returned by JsonObject.keySet and with instances of JsonArray, as shown in this example.

The navigateTree method for the model built in Creating an Object Model from Application Code produces the following output:

Key firstName: STRING Duke
Key lastName: STRING Java
Key age: NUMBER 18
Key streetAddress: STRING 100 Internet Dr
Key city: STRING JavaTown
Key state: STRING JA
Key postalCode: STRING 12345
Key phoneNumbers: ARRAY
Key type: STRING mobile
Key number: STRING 111-111-1111
Key type: STRING home
Key number: STRING 222-222-2222

Writing an Object Model to a Stream

The object models created in Creating an Object Model from JSON Data and Creating an Object Model from Application Code can be written to a stream using the JsonWriter class as follows:

import javax.json.JsonWriter;
StringWriter stWriter = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(stWriter);

String jsonData = stWriter.toString();

The Json.createWriter method takes an output stream as a parameter. The JsonWriter.writeObject method writes the object to the stream. The JsonWriter.close method closes the underlying output stream.

The following example uses try-with-resources to close the JSON writer automatically:

StringWriter stWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stWriter)) {

String jsonData = stWriter.toString();

Previous Next Contents
Oracle Logo  Copyright © 2017, Oracle and/or its affiliates. All rights reserved.