as3corelib Tutorial:How to Use JSON Class in Flex

Tooth-Toy-256x256 This class provides encoding and decoding of the JSON format. This demo shows how to encode an object to a JSON-formate string and how to decode a JSON-formate string to an object. It’s really simple with this class provided by as3corelib library.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

Please access www.json.org for more about JSON.

Search-256x256 Demo | DownloadDownload Full Project

Screenshot:

I create a complex object with the medthod initApp() in order to encode it to JSON format. The string returned by the method JSON.encode is displayed on the right of the panel. The properties of the complex object are displayed on the left.

JSON-Demo

With the content of the text area which contains returned string changed, the properties of the object are changed as well. For example, I change “id” into “objectId” with the content of text area on the rights, the line id(String):"userCollection" on the left is changed into objectId(String):"userCollection" as well. I use JSON.decode to get the a new object with changed properties, then parse the object properties to a well-formed string and display the string on the left.

Methods:

1. decode

public static function decode(s:String):*

Decodes a JSON string into a native object.

Parameters:

s:String The JSON string representing the object.

Returns:

* A native object as specified by s.

2. encode

public static function encode(o:Object):String

Encodes a object into a JSON string.

Parameters:

o:Object The object to create a JSON string for.

Returns:

String the JSON string representing o.

The following is full source code of XMLUtilDemo.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initApp()">
	<mx:Style>
		global
		{
			fontSize:14;
		}
	</mx:Style>
	<mx:Script>
		<![CDATA[
			import flash.utils.describeType;
			import mx.utils.ObjectUtil;
			import com.adobe.serialization.json.JSON;

			private var myObject:Object;

			[Bindable]
			private var encodedObjectString:String;

			[Bindable]
			private var decodedObjectString:String;

			private function initApp():void
			{
				myObject = new Object();

				myObject.id = "userCollection";
				myObject.users = new Array();

				for(var i:uint = 0 ;i < 2;i++)
				{
					var user:Object = new Object();
					user.name = "user" + i;
					user.password = "password" + i;
					user.login = i%2==0? true : false;
					user.role = new Object();
					user.role.name = "user";
					user.flags = new Array(1,2,3,4,5,6);
					(myObject.users as Array).push(user);
				}

				myObject.userCount = (myObject.users as Array).length;
				myObject.extension = null;
				myObject.flags = new Array("a","b","c",false,1,5,77,null);

				/* ************** encode myObject to JSON string ************** */
				encodedObjectString = JSON.encode(myObject);
				/* ************************************************************ */

				decodedObjectString = getDecodedObjectString(myObject);
			}

			private function getDecodedObjectString(obj:Object,level:int = 0):String
			{
				var prefix:String = "";
				for(var i:int = 0;i < level; i++)
				{
					prefix += "    ";
				}
				level++;

				var retValue:String = "";
				var objProperties:Object = ObjectUtil.getClassInfo(obj);

				if(objProperties.properties.length>0)
				{
					for each(var qname:QName in objProperties.properties)
					{
						var property:* = obj[qname.localName];
						var propertyType:String = getQualifiedClassName(property);

						switch(propertyType)
						{
							case "null":
								retValue += prefix + qname.localName + "(" + propertyType + ")" + ":" + property + "\n";
								break;
							case "String":
								retValue += prefix + qname.localName + "(" + propertyType + ")" + ":" + "\"" + property + "\"" + "\n";
								break;
							case "int":
								retValue += prefix + qname.localName + "(" + propertyType + ")" + ":" + property + "\n";
								break;
							case "Array":
								retValue += prefix + qname.localName + "(" + propertyType + ")" + ":" + "\n" + getDecodedObjectStringFromArray(property,level) + "\n";
								break;
							case "Object":
								retValue += prefix + qname.localName + "(" + propertyType + ")" + ":" + "\n" + getDecodedObjectString(property,level) + "\n";
								break;
							case "Boolean":
								retValue += prefix + qname.localName + "(" + propertyType + ")" + ":" + property + "\n";
								break;
						}
					}
				}
				return retValue;
			}

			private function getDecodedObjectStringFromArray(arr:Array,level:int):String
			{
				var prefix:String = "";
				for(var i:int = 0;i < level; i++)
				{
					prefix += "    ";
				}
				level++;

				var retValue:String = "";
				var index:int = 0;

				for each(var value:* in arr)
				{
					var type:String = getQualifiedClassName(value);

					switch(type)
					{
						case "null":
							retValue += (index == 0?prefix:"")  + "(" + type + ")" + value + ",";
							break;
						case "String":
							retValue += (index == 0?prefix:"")  + "(" + type + ")" + value + ",";
							break;
						case "int":
							retValue += (index == 0?prefix:"")  + "(" + type + ")" + value + ",";
							break;
						case "Array":
							retValue += prefix + "(" + type + ")" + getDecodedObjectStringFromArray(value,level);
							break;
						case "Object":
							retValue += prefix +  "(" + type + ")" + "\n" +getDecodedObjectString(value,level);
							break;
						case "Boolean":
							retValue += (index == 0?prefix:"")  + "(" + type + ")" + value + ",";
							break;
					}

					index++;
				}
				return retValue;
			}

			private function updateDecodedObjectString():void
			{
				try
				{
					/* ************** decode JSON string to an object ************** */
					myObject = JSON.decode(encodedString.text);
					/* ************************************************************* */
					decodedObjectString = getDecodedObjectString(myObject);
				}
				catch(e:Error)
				{

				}
			}
		]]>
	</mx:Script>
	<mx:Panel title="JSON Demo" width="100%" height="100%" layout="absolute">
		<mx:TextArea id="encodedString" text="{encodedObjectString}" width="50%" height="100%" right="0" top="0" change="updateDecodedObjectString()"/>
		<mx:VBox width="50%" left="0" height="100%">
			<mx:Label text="object properties" fontWeight="bold"/>
			<mx:TextArea editable="false" height="100%" width="100%" text="{decodedObjectString}"/>
		</mx:VBox>
	</mx:Panel>
</mx:Application>

Enjoy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

2 Responses to “as3corelib Tutorial:How to Use JSON Class in Flex”

  1. [...] as3corelib Tutorial:How to Use JSON Class in Flex – Ntt.cc (tags: json flex flash as3 tutorial) [...]

Leave a Reply to Corelib — An ActionScript 3 Library For Flex and Flash Developers | FlexMan