JSON Processing in JavaEE 7- Using Object Model API

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:

  1. Create a JsonReader to read from the input source i.e the string message.
  2. Extract the JsonArray from the input source
  3. Iterate through the JsonArray which is nothing but an implementation of Java List.
  4. 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.

Comments

comments

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Comments

  1. hammouda says:

    Hi,i create a json file which similare to this example and i try to read it with using jackson lib but i have an excption when i run my java class.
    this is my class:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.Map;

    import javax.json.Json;
    import javax.json.JsonArray;
    import javax.json.JsonObject;
    import javax.json.JsonReader;
    import org.json.JSONException;

    public class Read_Table_Json {
    private Map map;
    static String filepath = “C:\\Users\\topinfo\\Desktop\\user.json”;

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    new Read_Table_Json().parseFile(filepath);
    }

    public void parseFile(String file_path) {

    // JsonParser parser=new JsonParser(new
    // FileReader(“C:\\Users\\topinfo\\Desktop\\user.json”));
    // JsonArray array=((Object) parser).readValue();

    JsonReader reader = Json.createReader(new StringReader(file_path));
    JsonArray array = reader.readArray();
    for (int i = 0; i < array.size(); i++) {
    JsonObject jsonObject = array.getJsonObject(i);
    map.put(jsonObject.getString("Key"), jsonObject.getString("value"));
    for (String k : map.keySet()) {

    System.out.println(k + ": " + map.get(k));
    }

    }

    }

    }
    and this is the result after run:
    Exception in thread "main" javax.json.stream.JsonParsingException: Unexpected char=C
    at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:325)
    at org.glassfish.json.JsonParserImpl$StateIterator.nextToken(JsonParserImpl.java:158)
    at org.glassfish.json.JsonParserImpl$StateIterator.next(JsonParserImpl.java:183)
    at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:151)
    at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:125)
    at jsonLinkProject.Read_Table_Json.parseFile(Read_Table_Json.java:32)
    at jsonLinkProject.Read_Table_Json.main(Read_Table_Json.java:22)

    So please can you help me to resolve this problem ?

Speak Your Mind

*