Saturday 21 February 2015

JSON Read & Write with Java


JSON processing in Java is a new specification in JavaEE7 (JSR353).

Overview:
The acronym JSON means Javascript Object notation, and is a format for data interchange, as XML.

Below there is an example of a object : burguermenu represented in both JSON and in XML syntax:

Json syntax
{"menu":  {"type":"cheeseburguer", 
 "drink":"coke",
 "side":["chips","salad"]    
 }
}
XML syntax
<menu>
<type>cheeseburguer</type>    <drink>coke</drink>    <side>chips</side>    
<side>salad</side>
</menu>


To be able with deal with Json directly in Java we will need to import the package javax.json.* (Remeber this package is included in javaEE 7, and is not available in previous version). Alternatively you can download this library from https://jsonp.java.net/

There are two ways to perform I/O actions : ObjectModel and Streaming model
In this post we will explore the first one, with simple examples of reading and writing.

Create Json object in Java:

In the example a json object menu is created with JsonObjectBuilder:


Write a JsonObject --> obtain Json text

The method write the above object using JsonWriter
The output will be:
{"menu":{"type":"cheeseburguer","drinks":"coke","side":["chips","salad"]}}

Read Json text --> obtain a JsonObject

This method read the above output string using JsonReader and it will obtain a JsonObject The output will be:
{"type":"cheeseburguer","drinks":"coke","side":["chips","salad"]}
cheeseburguer
chips
salad


No comments:

Post a Comment