views:

1669

answers:

2

Are there any stream-reading, parsing libraries available for json or xml formats in AS3? I'm setting up a long-polling application, using URLStream/URLRequest. I do not have control over the data I'm receiving other than a choice between formats. I'd like to have a parser that can handle fragments at a time, which would allow me to trigger custom events when certain complete fragments become available. Thoughts? What are current AIR applications doing to handle this?

Sample API:

var decoder:StreamingJSONDecoder = new StreamingJSONDecoder();
decoder.attachEvent("onobjectavailable", read_object); 

while (urlStream.bytesAvailable) 
{
  decoder.readBytes(get_bytes(urlStream)); 
}
+1  A: 

Yup.

Have a look at the AS3 Corelib: http://code.google.com/p/as3corelib/

It's an Adobe library. There should be more info on labs.adobe.com.

I did have an issues with the RSS parser on the date format, but other than that, everything seemed fine.

Goodluck!

George Profenza
Correct me if I'm wrong, but I don't think the APIs provided by as3corelib support streaming. I added some sample code to my original question to clarify.
Sorry...I didn't read the question properly. The latest details on the as3 JSON library I read were here:http://www.darronschall.com/weblog/2008/12/as3-json-library-now-a-little-less-strict.cfm. Can't help much though :(
George Profenza
A: 

You could potentially use a URLStream instance to progressively download the data from a remote network, then decode the JSON result when enough data is available.

Something like this (not tested, just to give you an idea):

var stream:URLStream = new URLStream();
stream.addEventListener( ProgressEvent.PROGRESS, handleProgress );
stream.load( new URLRequest( "/path/to/data" ) );

function handleProgress( event:ProgressEvent ):void
{
    // Attempt to read as much from the stream as we can at this point in time
    while ( stream.bytesAvailable )
    {
        // Look for a JSONParseError if the JSON is not complete or not
        // encoded correctly.
        // Look for an EOFError is we can't read a UTF string completely
        // from the stream.
        try
        {
            var result:* = JSON.decode( stream.readUTF() );
            // If we're here, we were able to read at least one decoded JSON object
            // while handling this progress event
        }
        catch ( e:Error )
        {
            // Can't read, abort the while loop and try again next time we
            // get download progress.
            break;
        }
    }   
}
darronschall