Chapter 7. Data Transfer Additions

A robust application development platform needs a robust set of data transfer options. With the introduction of root level XML support along with the first release of Adobe AIR, developers could take advantage of any XML-based format within their applications. AIR 3 adds support for a native JSON handler and some great enhancements when working with sockets in communicating with various systems.

Native JSON (JavaScript Object Notation) Support

JavaScript Object Notation (JSON) is a hugely popular way of transporting structured data sets into and out of applications that run within AIR applications. Ever since ActionScript 3.0 was introduced, there have been third-party support libraries which allowed developers to use JSON in their projects quite easily; however, this is costly in terms of performance, since it was never a core function of AIR itself.

Note

JSON is a top level class, similar to the XML or Array classes present in ActionScript. As such, they do not need to be imported in order to be used within an application.

The following JSON object describes a person through a series of name value pairs. Notice that objects can be nested and that this syntax can even include array structures. It is incredibly flexible.

{
     "firstName": "Joseph",
     "lastName": "Labrecque",
     "address":
     {
         "streetAddress": "2199 S. University Blvd.",
         "city": "Denver",
         "state": "CO",
         "postalCode": "80208"
     },
     "phoneNumber":
     [
         {
           "type": "work",
           "number": "303.871.6566"
         },
         {
           "type": "fax",
           "number": "303.871.7445"
         }
     ]
}

JSON.parse()

We use this JSON file in the following code example to parse the values from the loaded JSON object using JSON.parse(), and then format the values within a basic TextField within our AIR Application

package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.text.TextField;
    import flash.text.TextFormat;

    [SWF(width="600", height="500", backgroundColor="#CCCCCC")]

    public class ReadJSON extends Sprite {

        private var traceField:TextField;
        private var json:URLLoader;
        private var parsedJSON:Object;

        public function ReadJSON() {
            generateDisplayObjects();
            performOperations();
        }

        protected function generateDisplayObjects():void {
            var defaultFormat:TextFormat = new TextFormat();
            defaultFormat.font = "Arial";
            defaultFormat.size = 26;
            defaultFormat.color = 0xFFFFFF;

            traceField = new TextField();
            traceField.backgroundColor = 0x000000;
            traceField.alpha = 0.7;
            traceField.width = stage.stageWidth;
            traceField.height = stage.stageHeight;
            traceField.wordWrap = true;
            traceField.multiline = true;
            traceField.background = true;
            traceField.defaultTextFormat = defaultFormat;
            addChild(traceField);
        }

        protected function performOperations():void {
            json = new URLLoader();
            json.addEventListener(Event.COMPLETE, parseJSON);
            json.load(new URLRequest("assets/data.json"));

            traceField.appendText("Loading JSON file...
");
        }

        protected function parseJSON(e:Event):void {
            traceField.appendText("JSON file loaded successfully!
");
            traceField.appendText("Parsing JSON...

");
            traceField.appendText("RESULTS:
");

            parsedJSON = JSON.parse(json.data);

            traceField.appendText("firstName: " + parsedJSON.firstName + "
");
            traceField.appendText("lastName: " + parsedJSON.lastName + "
");
            traceField.appendText("address.streetAddress: " + parsedJSON.address.streetAddress + "
");
            traceField.appendText("address.city: " + parsedJSON.address.city + "
");
            traceField.appendText("address.state: " + parsedJSON.address.state + "
");
            traceField.appendText("address.postalCode: " + parsedJSON.address.postalCode + "
");
            for(var i:int = 0; i<parsedJSON.phoneNumber.length; i++){
                traceField.appendText(parsedJSON.phoneNumber[i].type + ": " + parsedJSON.phoneNumber[i].number + "
");
            }
        }

    }
}

As you can see, dealing with JSON is very similar to dealing with XML within ActionScript. Parsing our imported JSON and outputting the data into a TextField renders similar to Figure 7-1.

Parsed JSON output

Figure 7-1. Parsed JSON output

JSON.stringify()

To actually write JSON from within an AIR project, we need to employ the JSON.stringify() method as demonstrated in the following code example.

package {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFormat;

    [SWF(width="600", height="500", backgroundColor="#CCCCCC")]

    public class WriteJSON extends Sprite {

        private var traceField:TextField;
        private var jsonObject:Object;

        public function WriteJSON() {
            generateDisplayObjects();
            performOperations();
        }

        protected function generateDisplayObjects():void {
            var defaultFormat:TextFormat = new TextFormat();
            defaultFormat.font = "Arial";
            defaultFormat.size = 26;
            defaultFormat.color = 0xFFFFFF;

            traceField = new TextField();
            traceField.backgroundColor = 0x000000;
            traceField.alpha = 0.7;
            traceField.width = stage.stageWidth;
            traceField.height = stage.stageHeight;
            traceField.wordWrap = true;
            traceField.multiline = true;
            traceField.background = true;
            traceField.defaultTextFormat = defaultFormat;
            addChild(traceField);
        }

        protected function performOperations():void {
            traceField.appendText("Forming Object in ActionScript...
");

            jsonObject = new Object();
            jsonObject.firstName = "Edgar";
            jsonObject.middleName = "Allan";
            jsonObject.lastName = "Poe";
            jsonObject.birthDate = 1809;
            jsonObject.deathDate = 1849;
            jsonObject.nationality = "American";
            jsonObject.birthPlace = "Boston, Massachusetts";

            traceField.appendText("Stringify in progress...

");

            var newJSON:Object = JSON.stringify(jsonObject, null, 4);

            traceField.appendText("RESULT:
");
            traceField.appendText(newJSON.toString());
        }

    }
}

The JSON.stringify() method will convert the ActionScript object we’ve assembled into complete JSON syntax. This assumes that all data types within the object are of a type that can be converted into JSON.

Note

Valid data types include: Array, String, Number, Boolean, and null.

The first argument that we pass into this method is the actual object which we want to convert. The second argument is an optional replacer function (or array) that can be used to transform or filter the key/value pairs in the object to be converted. This could be used in case we want to exclude certain key/value pairs, for instance, from the actual output.

The final argument specifies the amount of spaces to insert before each piece of data in order to make it more human-readable. In this example, we are passing in the number 4, specifying that the method should prepend 4 whitespace characters before each entry. This is how we achieve the spacing and readability in Figure 7-2.

Stringified object output

Figure 7-2. Stringified object output

Figure 7-2 demonstrates the stringified output from our example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset