# The Java EE 7 Tutorial

# 19.3 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.

## 19.3.1 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 java.io.FileReader;
    import javax.json.Json;
    import javax.json.JsonReader;
    import javax.json.JsonStructure;
    ...
    JsonReader reader = Json.createReader(new FileReader("jsondata.txt"));
    JsonStructure jsonst = reader.read();

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.

## 19.3.2 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(Json.createObjectBuilder()
             .add("type", "mobile")
             .add("number", "111-111-1111"))
          .add(Json.createObjectBuilder()
             .add("type", "home")
             .add("number", "222-222-2222")))
       .build();

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.

## 19.3.3 Navigating an Object Model

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:
             System.out.println("OBJECT");
             JsonObject object = (JsonObject) tree;
             for (String name : object.keySet())
                navigateTree(object.get(name), name);
             break;
          case ARRAY:
             System.out.println("ARRAY");
             JsonArray array = (JsonArray) tree;
             for (JsonValue val : array)
                navigateTree(val, null);
             break;
          case STRING:
             JsonString st = (JsonString) tree;
             System.out.println("STRING " + st.getString());
             break;
          case NUMBER:
             JsonNumber num = (JsonNumber) tree;
             System.out.println("NUMBER " + num.toString());
             break;
          case TRUE:
          case FALSE:
          case NULL:
             System.out.println(tree.getValueType().toString());
             break;
       }
    }

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:

    OBJECT
    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
    OBJECT
    Key type: STRING mobile
    Key number: STRING 111-111-1111
    OBJECT
    Key type: STRING home
    Key number: STRING 222-222-2222

## 19.3.4 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 java.io.StringWriter;
    import javax.json.JsonWriter;
    ...
    StringWriter stWriter = new StringWriter();
    JsonWriter jsonWriter = Json.createWriter(stWriter);
    jsonWriter.writeObject(model);
    jsonWriter.close();

    String jsonData = stWriter.toString();
    System.out.println(jsonData);

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)) {
       jsonWriter.writeObject(model);
    }

    String jsonData = stWriter.toString();
    System.out.println(jsonData);