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;
    }

}

Was this information helpful? Send us your comments.