Over a million developers have joined DZone.

EE7 JSON-P API in a Nutshell

· Integration Zone

Build APIs from SQL and NoSQL or Salesforce data sources in seconds. Read the Creating REST APIs white paper, brought to you in partnership with CA Technologies.

JSON, JavaScript Object Notation, is a data structure that is language and platform neutral, easily human readable and writable. Since it is also based on the syntax for how objects and their properties are represented in JavaScript in a textural form, it’s easy to produce and consume in JavaScript by your webapp client in your browser.

JSON and JSON-P – Getting Started

If you’re not as familiar with JSON, take a look at the json.org site to get a good overview. Since the JSON-P API is part of EE7, you can also follow the Java EE7 Tutorial section on JSON-P which covers the API in more detail than I’ll cover there, but it’s really very simple.

Let’s look at a simple example to get started – assuming we have a JSON document representing a Customer, that looks like this:

{
  "firstName" : "John",
  "lastName" : "Smith",
  "phoneNumber" : "111 222 1234"
}

This document has 3 properties, firstName, lastName, and phoneNumber, with String values.

To generate this using Java code, we could do some simple String concatenation of the static property names and append the values into the String, but that is clumsy and error prone – this is where the JSON-P API comes in. JSON-P uses the ‘builder pattern’ to add attributes to a document:

JsonObject jsonObject = Json.createObjectBuilder()
    .add("firstName", "John")
    .add("lastName", "Smith")
    .add("phoneNumber", "111 222 1234").build();

Json.createObjectBuilder() creates the builder, and then we can repeatedly call the add() method to add our attributes to the document, giving the attribute name and value. When we’ve completed adding attributes, we call the build() method, and it returns an instance of JsonObject, which is an object representation of the document that we just constructed.

To return the created document as a String, use JsonWriter with a StringWriter:

StringWriter sw = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(sw);
jsonWriter.write(jsonObject);
jsonWriter.close();
String json = sw.toString();


Creating Nested Documents

What if we need to create something more complex, with nested documents? If we want to represent our phoneNumber property as a nested document to capture the type of phone number, like this:

{
  "firstName" : "John",
  "lastName" : "Smith",
  "phoneNumber" : {
    "phoneNumberType" : "home",
    "number" : "111 222 1234"
  }
}

To create a nested document we can use the Json.createObjectBuilder() again to create the nested document just like we did for the outer document and assign it’s value to the phoneNumber property like this:

JsonObject jsonObject = Json.createObjectBuilder()
    .add("firstName", "John")
    .add("lastName", "Smith")
    .add("phoneNumber", Json.createObjectBuilder()
        .add("phoneNumberType", "home")
        .add("number", "111 222 1234").build())
    .build();

Creating Arrays of Documents

If in our example we need to include an array of phone numbers of different types (home, work, etc) then we need to use another JSON-P API, JsonArrayBuilder. If our document needs to look like this:

{
  "firstName" : "John",
  "lastName" : "Smith",
  "phoneNumbers" : [ 
    {
      "phoneNumberType" : "home",
      "number" : "111 222 1234"
    },
    {
      "phoneNumberType" : "work",
      "number" : "222 222 2244"
    }    
  ]
}

...then can we create it like this, breaking the creation into two steps. First create the array of phone numbers using JsonArrayBuilder:

//build array of phone numbers using JsonArrayBuilder
JsonArrayBuilder phoneNumberArrayBuilder = Json.createArrayBuilder();

//create and add: home phone number
phoneNumberArrayBuilder.add(Json.createObjectBuilder()
    .add("phoneNumberType", "home")
    .add("number", "111 222 1234").build());

//create and add: work phone number
phoneNumberArrayBuilder.add(Json.createObjectBuilder()
    .add("phoneNumberType", "work")
    .add("number", "222 333 4444").build());

Next, create the document as before, and add the JsonArrayBuilder as the value for the phoneNumbers property:

//now build doc as before, including arraybuilder for the phoneNumbers array
JsonObject jsonObject = Json
    .createObjectBuilder()
    .add("firstName", "John")
    .add("lastName", "Smith")
    .add("phoneNumbers", phoneNumberArrayBuilder)
    .build();

Summary

This article has introduced the basic steps needed to build JSON documents using EE7's JSON-P API, using JsonObjectBuilder and JsonArrayBuilder APIs. This approach builds an in-memory object model of a JSON document which you can write out to a String as needed. Alternatively, the JSON-P API also includes a ‘streaming’ API which can parse and create ‘on the fly’, similar to the SAX API approach in JAXP for parsing XML.


For more information, see:

JSON-P (JSR 353) – Java API for JSON Processing

JSON-P Project Homepage: https://jsonp.java.net/

Java EE7 Tutorial – JSON-P: http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm


The Integration Zone is brought to you in partnership with CA Technologies.  Use CA Live API Creator to quickly create complete application backends, with secure APIs and robust application logic, in an easy to use interface.

Topics:
java ,opinion ,enterprise-integration ,json ,integration ,java ee7 ,json-p

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}