Big Data/Analytics Zone is brought to you in partnership with:

Java Developer | Technical Teacher | Author of "Java Mimarisiyle Kurumsal Çözümler" Rahman has posted 11 posts at DZone. You can read more from them at their website. View Full User Profile

Java API for JSON Processing – Creating JSON Objects

06.22.2013
| 22996 views |
  • submit to reddit

Java API for JSON Processing (JSON-P) is a Java Standard defined with the JSR-353, which  is a part of Java EE 7. It is called JSON-P as abbreviation but it does not seem appropriate because of causing confusion with JSON Padding. For this reason, it may cause confusion at first glance but even so, I would prefer JSON-P abbreviation in this article.

The irreducible rise of the RESTful web services has provided JCP to give more proclivities to this process and make them enter into the process of establishing a standard for the manipulation of JSON in Java EE 7. People who deal with XML technologies are familiar with Stax and DOM technologies that are used on behalf of processing and managing XML. General libraries about Stax and DOM already exist for a long time, which are for XML data exchange format in Java SE. Now, Stax and DOM approaches used for XML together with JSON-P will be introduced in a manner similar to JSON.

Although there exists libraries on the basis of Stax and DOM in JSON-P, there were not any APIs which undertake the conversion of Object<>JSON as similar to JAXB. If you develope Restful Webservices with Jax-RS before, software exist in Java ecosystem such as Jackson, Jettison was already being used for Json Binding operations. These operations in JAX-RS was being resolved by converting the object into XML format previously and then converting the converted XML data in JSON format. But with Jax-RS 2 and Json-P, container can convert Json based Java objects to Json representation and vice verse.

As you can access to the JSON-P project from the http://json-processing-spec.java.net/address, you can also use dependency where libraries exist through the following Maven dependency component.

<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0</version>
</dependency>

Now I want to give you examples about how to build JSON objects with JSON-P.
Whereas a simple JSON object accepts data in the { [ key ]:[ value ] , .. } format,
A simple JSON array accepts data in the [ val1,val2, .. , val3 ] format.


Example 1: A simple JSON object

JSON Format

{
  "name": "Fikret",
  "surname": "Savaş",
  "age": 25
}

JsonObject Representation

JsonObject jsonObject1 =
        Json.createObjectBuilder()
                .add("name", "Fikret")
                .add("surname", "Savaş")
                .add("age", 25)
        .build();


Example 2: A complex array of Json which hosts Json object
JsonArray object in JSON-P can accept such components in the type of String, int, double, boolean, BigInteger, BigDecimal. In addition, it also accepts objects in the type of JsonValue interface (such as JsonObject, JsonArray).

JSON Format

[
  "A",
  5,
  6.3,
  false,
  30,
  {
    "name": "Fikret",
    "surname": "Savaş",
    "age": 25
  }
]

JsonArray Representation

JsonArray jsonArray1= Json.createArrayBuilder()
        .add("A") // String
        .add(5)   // int
        .add(6.3) // double
        .add(false)  // boolean
        .add(new BigInteger("30"))  // Big(Integer) | (Decimal)
        .add(jsonObject1)  // JsonValue
        .build();

Example 3: A Json object which hosts Json array


JSON Format

{
  "name": [
    "Emin",
    "Şahin"
  ],
  "surname": "Demir"
}

JsonObject Representation

JsonArray jsonArray2=Json.createArrayBuilder()
        .add("Emin").add("Şahin").build();
JsonObject jsonObject2 = Json.createObjectBuilder()
        .add("name", jsonArray2)
        .add("surname", "Demir")
        .build();

Example 4: A complex Json object


JSON Format

{
  "name": "Ersin",
  "surname": "Çetinkaya",
  "age": 25,
  "address": {
    "city": "Bursa",
    "country": "Türkiye",
    "zipCode": "33444"
  },
  "phones": [
    "234234242",
    "345345354"
  ]
}

JsonObject Representation

JsonObject jsonObject3 =
    Json.createObjectBuilder()
        .add("name", "Ersin")
        .add("surname", "Çetinkaya")
        .add("age", 25)
        .add("address",
              Json.createObjectBuilder()
                  .add("city", "Bursa")
                  .add("country", "Türkiye")
                  .add("zipCode", "33444"))
        .add("phones",
                      Json.createArrayBuilder()
                          .add("234234242")
                          .add("345345354"))
        .build();

The real content and sample codes can be access at http://en.kodcu.com/2013/06/java-api-for-json-processing-creating-json-objects/

Hope to see you again.

Published at DZone with permission of its author, Rahman Usta.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Yair Ogen replied on Sun, 2013/06/23 - 1:59am

How is the perfoamance compared to other libraries (say Jackson for example)?

Chege Kinuthia replied on Wed, 2013/07/24 - 9:12am

Assuming you have a json string produced by twitter api like https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline


How would you create a json object and parse it?


Thanks.

Rahman Usta replied on Sat, 2013/07/27 - 6:11am in response to: Chege Kinuthia

Hi Chege, you can follow next article -> http://java.dzone.com/articles/java-api-json-processing-%E2%80%93-0

Kumar Baki replied on Wed, 2013/12/11 - 6:50am

How to Read and Write Json in java?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.