Tuesday, August 9, 2011

Parsing In LWUIT & LWUIT4IO

Generally LWUIT as a UI framework focuses on the visual aspect of things and not so much on the unsexy backend logic such as parsing. However, thanks to Ofir we now have an HTMLComponent that included within it a parser for XML which now has its own public API.

Normally we would all try to reuse code from existing projects such as kXML etc. however due to licensing conflicts and the requirement to get permissions from management for every dependency we tend to just solve problems by writing code which is easier than going through the Sun/Oracle bureaucracy.

In LWUIT4IO I needed and subsequently wrote a JSON parser as well which allowed me to easily traverse results for queries to Google, Facebook and other API's. So now LWUIT includes two separate API's allowing you to parse server responses whether in XML or in JSON.

Using both API's is rather simple and both API's include two versions: Parse Tree or Event based.The parse tree approach returns a data structure containing the parse data, for JSON this is a simple Hashtable with nested data structures. For XML this is an element node that can contain the whole XML hierarchy.

The event based approach allows subclassing the parser and overriding key methods within it to store the data in the way you see fit.

XML can be parsed by creating an instance of XMLParser and invoking the parse() method on that instance, which returns the root Element object for the XML tree. Alternatively the XMLParser class can be subclassed and the eventParser() method invoked, this will be followed by callbacks to the methods: startTag, endTag, attribute & textElement all of which can be overriden to provide custom behavior.

The JSONParser class allows us to parse JSON data either by using the static parse method which provides callbacks to the JSONParseCallback interface thus providing events of the data within the JSON structure. It also contains an instance method named parse() that returns a Hashtable containing the resulting JSON structure, this structure is a set of nested Strings, Hashtables and Vectors to match the JSON JavaScript based hierarchy.

You can take a look at the LWUIT4IO services package source code to see samples of how we use these parsers to implement several builtin services.