Parsing a common Internet data format

You can configure a Destination object to return a Java® object that contains data parsed from a standard format, such as JSON. To retrieve the data structure in a Java object, you should:
  1. Specify a MessageProcessor object when you invoke DestinationFactory.create...().
  2. Retrieve the response from your Destination.
  3. Extract the data from the Message object that is returned in the response.

Code sample

The following code sample demonstrates the three actions that are required to retrieve a Java object that contains a JSON data structure.

import net.rim.device.api.io.messaging.*
import net.rim.device.api.io.parser.json.*

// Specify a MessageProcessor when you create your Destination
BlockingSenderDestination bsd = DestinationFactory(myContext, myURI,
                          new JSONMessageProcessor());

// Retrieve the response
Message response = bsd.sendReceive();

// Extract the Java object that contains the JSON data structure
Object payload = response.getObjectPayload();

Parse a JSON data structure

This task uses a TreeField to display the contents of a JSON data structure.
Before you begin: Retrieve a Java® object that contains a JSON data structure. Pass that object to the constructor of the class developed in this task.
  1. Import the required classes and interfaces.
    import net.rim.device.api.ui.*;
    import net.rim.device.api.ui.component.*;
    import net.rim.device.api.ui.container.MainScreen;
  2. Define a MainScreen class that implements TreeFieldCallback interface.
    public class JSONOutputScreen extends MainScreen implements TreeFieldCallback
    {
    
        private TreeField _treeField;
  3. Create a constuctor that accepts an Object as a parameter, creates the UI, and initiates the parsing code.
        public JSONOutputScreen(Object JSONData)
        {
            _treeField = new TreeField(this, Field.FOCUSABLE);
            add(_treeField);
            initializeTree(JSONData);
        }
  4. Create an initializeTree() method to clear any existing data from the TreeField.
        void initializeTree(Object obj)
        {
            int parentNode = 0;
    
            _treeField.deleteAll();
  5. Determine whether the current node in the JSON object is a JSONArray or a JSONObject. Invoke the appropriate populateTreeArray() method.
            try
            {
                if(obj instanceof JSONArray)
                {
                    parentNode = populateTreeArray
                                     (_treeField, 
                                      (JSONArray) obj, 
                                      parentNode);
                }
                else if(obj instanceof JSONObject)
                {
                    parentNode = populateTreeObject
                                     (_treeField, 
                                      (JSONObject) obj, 
                                      parentNode);
                }
            }
  6. Catch any errors, and specify where the TreeField should add new data.
            catch(JSONException e)
            {
                // Process error
            }
    
            _treeField.setCurrentNode(parentNode);
        }
  7. Implement populateTreeArray(TreeField, JSONArray, int).
        int populateTreeArray(TreeField tree, JSONArray o, int p) throws JSONException
        {
            Object temp;
  8. Add a node to the TreeField.
            int newParent = tree.addChildNode(p, "Array " + p);
  9. Iterate through the elements in this node of the JSONArray.
            for(int i = 0; i < o.length(); ++i)
            {
  10. Retrieve the current JSONArray.
                temp = o.get(i);
  11. If the node is empty, go to the next node.
                if(temp == null || temp.toString().equalsIgnoreCase("null"))
                {
                    continue;
                }
  12. If this node contains a nested JSON structure, parse the object recursively. Again, choose the most appropriate version of populateTreeArray().
                if(temp instanceof JSONArray)
                {
                    populateTreeArray(tree, (JSONArray) temp, newParent);
                }
                else if(temp instanceof JSONObject)
                {
                    populateTreeObject(tree, (JSONObject) temp, newParent);
                }
  13. This node must contain data. Add the data to the tree.
                else
                {
                    newParent = tree.addSiblingNode(newParent, temp.toString());
                }
            }
    
            return newParent;
        }
  14. Implement populateTreeArray(TreeField, JSONObject, int). The code is similar to steps 7 through 13, with the following alterations:
    1. Change the method signature from step 7.
          int populateTreeArray(TreeField tree, JSONObject o, int p) throws JSONException
          {
    2. Create a JSONArray containing the names of the elements.
              JSONArray jsonArray = o.names();
      
    3. Iterate over the newly created JSONArray instead of the JSONObject passed as a parameter. For more information, see step 9.
              for(int i = 0; i < jsonArray.length(); ++i)
              {
    4. From the JSONObject, retrieve the value for each name in jsonArray. For more information, see step 10.
                  temp = o.get(jsonArray.getString(i));
    5. Ensure that you add both the name and value to the tree. For more information, see step 13.
                      tree.addSiblingNode(newParent, a.getString(i) + ": " + temp.toString());
  15. Implement DrawTreeItem().
        public void drawTreeItem(TreeField treeField, Graphics graphics, int node,
                int y, int width, int indent) {
            if(treeField == _treeField)
            {
                Object cookie = _treeField.getCookie(node);
                if(cookie instanceof String)
                {
                    String text = (String) cookie;
                    graphics.drawText(text, indent, y, Graphics.ELLIPSIS, width);
                }
            }
    
        }
    }
Back To Top

Code sample: Parsing a JSON data structure

The following code sample demonstrates one way to parse a JSON data structure. You can use a similar process to parse JSON or other data formats that are provided by the Message Processing API.

import net.rim.device.api.io.URI;
import net.rim.device.api.io.messaging.*;
import net.rim.device.api.ui.*
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import java.io.*;
import org.json.me.*;

public class NetworkSample extends UiApplication 
{
    public static void main(String[] args) 
    {
        NetworkSample app = new NetworkSample();
        app.enterEventDispatcher();
    }
    public NetworkSample() 
    {
        pushScreen(new ParseJSONSample());
    }
}

class ParseJSONSample extends MainScreen implements FieldChangeListener
{

    ButtonField _btnJSON = new ButtonField(Field.FIELD_HCENTER);

    private static UiApplication _app = UiApplication.getUiApplication();

    public ParseJSONSample()
    {
        _btnJSON.setChangeListener(this);
        _btnJSON.setLabel("Fetch page");

        add(_btnJSON);
    }

    public void fieldChanged(Field button, int unused)
    {

        if(button == _btnJSON)
        {

            Thread t = new Thread(new Runnable() 
            {
                public void run()
                {
                    Message response = null;
                    String uriStr = "http://docs.blackberry.com/sampledata.json"; 
                    BlockingSenderDestination bsd = null;
                    try
                    {
                        bsd = (BlockingSenderDestination)
                                    DestinationFactory.getSenderDestination
                                        ("CommAPISample", URI.create(uriStr));
                        if(bsd == null)
                        {
                            bsd =
                              DestinationFactory.createBlockingSenderDestination
                                  (new Context("CommAPISample"),
                                   URI.create(uriStr), new JSONMessageProcessor()
                                   );
                        }

                        // Send message and wait for response
                        response = bsd.sendReceive();
                        _json = response.getObjectPayload();

                        if(_json != null)
                        {
                            _app.invokeLater(new Runnable() 
                            {

                                public void run() 
                                {
                                    _app.pushScreen(new JSONOutputScreen(_json));
                                }

                            });
                        }
                    }
                    catch(Exception e)
                    {
                        System.out.println(e.toString());
                    }
                    finally
                    {
                        if(bsd != null)
                        {
                            bsd.release();
                        }
                    }
                }


            });
            t.start();

        }

}

class JSONOutputScreen extends MainScreen implements TreeFieldCallback 
{

    private TreeField _treeField;

    public JSONOutputScreen(Object JSONData)
    {
        _treeField = new TreeField(this, Field.FOCUSABLE);
        add(_treeField);
        setTree(JSONData);
    }

    void setTree(Object obj)
    {
        int parentNode = 0;

        _treeField.deleteAll();

        try
        {
            if(obj instanceof JSONArray)
            {
                parentNode = populateTreeArray
                                  (_treeField, (JSONArray) obj, parentNode);
            }
            else if(obj instanceof JSONObject)
            {
                parentNode = populateTreeObject
                                 (_treeField, (JSONObject) obj, parentNode);
            }
        }
        catch(JSONException e)
        {
            System.out.println(e.toString());
        }

        _treeField.setCurrentNode(parentNode);
    }


    // Populate the trees with JSON arrays
    int populateTreeArray(TreeField tree, JSONArray o, int p) throws JSONException
    {
        Object temp;
        int newParent;

        newParent = tree.addChildNode(p, "Array " + p);

        for(int i = 0; i < o.length(); ++i)
        {
            temp = o.get(i);

            if(temp == null || temp.toString().equalsIgnoreCase("null"))
            {
                continue;
            }

            if(temp instanceof JSONArray)
            {
                 // Array of arrays
                populateTreeArray(tree, (JSONArray) temp, newParent);
            }
            else if(temp instanceof JSONObject)
            {
                // Array of objects
                populateTreeObject(tree, (JSONObject) temp, newParent);
            }
            else
            { // other values
                newParent = tree.addSiblingNode(newParent, temp.toString());
            }
        }

        return newParent;
    }


    // Populate the tree with JSON objects
    int populateTreeObject(TreeField tree, JSONObject o, int p) throws JSONException
    {
        Object temp;

        int newParent = tree.addChildNode(p, "Object" + p);

        JSONArray a = o.names();

        for(int i = 0; i < a.length(); ++i)
        {
            temp = o.get(a.getString(i));

            if(temp == null || temp.toString().equalsIgnoreCase("null"))
            {
                continue;
            }
            if(temp instanceof JSONArray)
            {
                populateTreeArray(tree, (JSONArray) temp, newParent);
            }
            else if(temp instanceof JSONObject)
            {
                populateTreeObject(tree, (JSONObject) temp, newParent);
            }
            else
            {
                tree.addSiblingNode
                        (newParent, a.getString(i) + ": " + temp.toString());
            }
        }

        return newParent;
    }


    public void drawTreeItem(TreeField treeField, Graphics graphics, int node,
            int y, int width, int indent) 
    {
        if(treeField == _treeField)
        {
            Object cookie = _treeField.getCookie(node);
            if(cookie instanceof String)
            {
                String text = (String) cookie;
                graphics.drawText(text, indent, y, Graphics.ELLIPSIS, width);
            }
        }

    }

    public boolean onSavePrompt()
    {
        // Suppress the save dialog
        return true;
    }

}
Back To Top

Was this information helpful? Send us your comments.