Quantcast
Channel: Oracle Bloggers
Viewing all articles
Browse latest Browse all 19780

JsonGenerator and JsonObjectBuilder - Streaming and Object API in Java API for JSON Processing (TOTD #205)

$
0
0

Java API for JSON Processing (JSR 353) cleared Public Review unanimously and is on its way to to standardization. There is still Proposed Final Draft and the final vote to come. As per the Java EE 7 schedule, the specification will be final on 4/15/2013. The implementation is already integrated in GlassFish 4 builds.

The API provides an Object Model (like DOM for XML) and Streaming API (like StAX for XML) to parse and generate JSON structure. Here is a table that provide code fragments for generating some common JSON:

JSON Object Model API Streaming API
{ }
JsonObject jsonObject =
     new JsonObjectBuilder().build();

new JsonWriter(System.out)
     .writeObject(jsonObject);

JsonGeneratorFactory factory =
     Json.createGeneratorFactory();

JsonGenerator gen =
     factory.createGenerator(System.out);

gen.writeStartObject().writeEnd();
{
  "apple":"red",
  "banana":"yellow"
}
new JsonObjectBuilder()
  .add("apple", "red")
  .add("banana", "yellow")
.build();
gen.writeStartObject()
     .write("apple", "red")
     .write("banana","yellow")
   .writeEnd();
[
  { "apple":"red" },
  { "banana":"yellow" }
]
JsonArray jsonArray = new JsonArrayBuilder()
  .add(new JsonObjectBuilder()
          .add("apple","red"))

  .add(new JsonObjectBuilder()
          .add("banana","yellow"))

  .build();
gen.writeStartArray()
     .writeStartObject()
       .write("apple", "red")
     .writeEnd()
     .writeStartObject()
       .write("banana", "yellow")
     .writeEnd()
.writeEnd();
{
  "title":"The Matrix",
  "year":1999,
  "cast":[
    "Keanu Reaves",
    "Laurence Fishburne",
    "Carrie-Anne Moss"
  ]
}
new JsonArrayBuilder()
  .add(new JsonObjectBuilder()
  .add("title", "The Matrix")
  .add("year", 1999)
  .add("cast", new JsonArrayBuilder()
  .add("Keanu Reaves")
  .add("Laurence Fishburne")
  .add("Carrie-Anne Moss")))
.build();
gen.writeStartObject()
     .write("title", "The Matrix")
     .write("year", 1999)
     .writeStartArray("cast")
       .write("Keanu Reaves")
       .write("Laurence Fishburne")
       .write("Carrie-Anne Moss")
     .writeEnd()
   .writeEnd();

The source code for this sample can be downloaded here, try it with GlassFish 4 b76 or later.

Here are some more links for you to read further:


Viewing all articles
Browse latest Browse all 19780

Trending Articles