package com.ericfeminella.json
{
import com.adobe.serialization.json.JSON;
import mx.collections.ArrayCollection;
import mx.rpc.http.HTTPService;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.IResponder;
[Bindable]
/**
* Provides an API for working with JSON objects (JavaScript Object Notation)
*/
public class JSONDecoder implements IResponder
{
public var jsonCollection:ArrayCollection;
private static const FAULT:String = "Error Loading JSON Object from specified URI";
/**
* Loads a JSON object from the specified uri
*
* @param the uri in which the object resides
*/
public function loadJSON(uri:String):void
{
var service:HTTPService = new HTTPService();
service.url = uri;
service.useProxy = false;
service.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
service.addEventListener(ResultEvent.RESULT, this.result);
service.addEventListener(FaultEvent.FAULT, this.fault);
service.send();
}
/**
* Returns a native ArrayCollection implementation of the JSON object
*/
public function getJSONCollection():ArrayCollection
{
return this.jsonCollection;
}
/**
* Decodes raw JSON object to an Array which is referenced as
* the collection of JSON objects
*
* @param the result object returned from the call
*/
public function result(data:Object):void
{
var result:ResultEvent = data as ResultEvent;
var rawJSON:String = result.result.toString();
var arr:Array = JSON.decode(rawJSON) as Array;
this.jsonCollection = new ArrayCollection(arr);
}
/**
* Throws an error epecifying details specific to the JSONDecoder Error
*
* @param the fault object returned from the call
*/
public function fault(info:Object):void
{
var fault:FaultEvent = info as FaultEvent;
throw new Error (FAULT + fault.fault.message);
}
}
}