In my previous post about JSON processing I introduced you to the sample application and then showed how one can make use of the Streaming API to parse the JSON data. The JSON Streaming API was not suited for scenarios explained in my previous post. In such scenarios one can make use of the Object Model API to parse the JSON data.
Sample JSON Data for reference
Lets consider the JSON data we had generated in our previous post:
[ { "key":"sticky_1381306898171", "value":"how aout his" }, { "key":"sticky_1381306902222", "value":"Another one" }, { "key":"sticky_1381309254661", "value":"adding few more ..." } ]
And consider the websocket code from the previous post:
import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** * Demo for parsing the JSON using Streaming API. */ @ServerEndpoint("/saveStickNotes") public class TodoApplicationEndPoint { private Map<String, String> stickyNotes; @OnMessage public void receiveMessage(String message, Session session){ parseUsingStreamingAPI(message); parseUsingObjectAPI(message); } private void parseUsingStreamingAPI(String message) { //Parsing JSON data using Streaming API //Check the previous post in this series to get implementation of this method. } private void parseUsingObjectAPI(String message) { //TODO: Parsing the JSON data using Object Model API //This method implementation will be shown in this post. } }
In the above code I have removed the implementation of the method parseUsingStreamingAPI
and the same can be seen in the previous post. In this article the focus will be on implementing the method parseUsingObjectAPI
.
Important classes to be aware of to understand Object Model API
The various classes which one should be familiar with to understand and using the Object Model API to parse JSON data are:(Here I am only going to list classes for parsing, in my next post I will show how one can create JSON data and also list the classes used for it)
- JsonReader: Reads a JSON object or an array structure from an input source. The class Json contains methods to create readers from input sources (InputStream and Reader).
- JsonArray: JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array.
- JsonObject: JsonObject class represents an immutable JSON object value (an unordered collection of zero or more name/value pairs). It also provides unmodifiable map view to the JSON object name/value mappings.
In the sample shown in this article I am going to make use of the above three classes to parse the JSON data.
Parsing the JSON Data using Object Model API
Now that you have seen the structure of our JSON data as well as the various classes we would be using, lets get to the actual code which does the parsing. If you look at the JSON data shown above (If you are not familiar with JSON please read What is JSON?) you can see that its an array of different JSON Objects. So when we start parsing the JSON data we should extract the JSON Array and then iterate through that list to extract individual JSON objects. The individual JSON object contain the name-value pair data which can be extracted using the getXXX(key)
methods defined in the JsonObject
class.
The code below shows how to parse the Object Model API:
import java.io.StringReader; import java.util.HashMap; import java.util.Map; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** * Demo for parsing the JSON using Streaming API. */ @ServerEndpoint("/saveStickNotes") public class TodoApplicationEndPoint { private Map<String, String> stickyNotes; @OnMessage public void receiveMessage(String message, Session session){ parseUsingObjectAPI(message); } private void parseUsingObjectAPI(String message) { JsonReader reader = Json.createReader(new StringReader(message)); JsonArray array = reader.readArray(); stickyNotes = new HashMap<>(); for(int i = 0 ; i < array.size(); i++){ JsonObject jObj = array.getJsonObject(i); stickyNotes.put(jObj.getString("key"), jObj.getString("value")); } //Printing the sticky note data to verify that we have correctly parsed the data. for(String k : stickyNotes.keySet()){ System.out.println(k+": "+ stickyNotes.get(k)); } } }
In the above code the highlighted lines of code do the following:
- Create a JsonReader to read from the input source i.e the string message.
- Extract the JsonArray from the input source
- Iterate through the JsonArray which is nothing but an implementation of Java List.
- Fetch the JsonObject and then extract the required key and value data.
If you want to try this code, please replace the method parseUsingStreamingAPI
in my previous post with the method parseUsingObjectAPI
implemented in this post. After reading this article, you must be familiar with JSON Processing in JavaEE 7- Using Object Model API. If you have any questions on this topic, please write it in the comments section.