Michael Rochelle
unread,Jun 15, 2009, 8:43:01 PM6/15/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to ActionScript 3 Core Library
Hello,
I made a change to the JSONEncoder.as file that allows it to serialize
dynamic class instances properly. it will now serialize both dynamic
and declared variables.
Here are my changes starting at line #230:
/**
* Converts an object to it's JSON string equivalent
*
* @param o The object to convert
* @return The JSON string representation of <code>o</code>
*/
private function objectToString( o:Object ):String
{
// create a string to store the object's jsonstring value
var s:String = "";
// determine if o is a class instance or a plain object
var classInfo:XML = describeType( o );
var isObject:Boolean = (classInfo.@name.toString() == "Object");
var isDynamic:Boolean = (classInfo.@isDynamic.toString() ==
"true");
if (isDynamic) // Is a Dynamic Class Instance
{
var dynamicJson:String = getDynamicValues(o);
var declaredJson:String = getDeclaredValues(o);
if (dynamicJson.length > 0)
{
s = dynamicJson;
}
if (declaredJson.length > 0)
{
if (s.length > 0)
s += ",";
s += declaredJson;
}
}
else
if (isObject) // Is a Generic Object
{
s = getDynamicValues(o);
}
else // o is a class instance
{
s = getDeclaredValues(o);
}
return "{" + s + "}";
}
private function getDynamicValues(o:Object):String
{
var s:String = "";
// the value of o[key] in the loop below - store this
// as a variable so we don't have to keep looking up o[key]
// when testing for valid values to convert
var value:Object;
// loop over the keys in the object and add their converted
// values to the string
for ( var key:String in o )
{
// assign value to a variable for quick lookup
value = o[key];
// don't add function's to the JSON string
if ( value is Function )
{
// skip this key and try another
continue;
}
// when the length is 0 we're adding the first item so
// no comma is necessary
if ( s.length > 0 )
{
// we've already added an item, so add the comma separator
s += ","
}
s += escapeString( key ) + ":" + convertToString( value );
}
return s;
}
private function getDeclaredValues(o:Object):String
{
var s:String = "";
var classInfo:XML = describeType( o );
// Loop over all of the variables and accessors in the class and
// serialize them along with their values.
for each ( var v:XML in classInfo..*.( name() == "variable" || name
() == "accessor" ) )
{
// When the length is 0 we're adding the first item so
// no comma is necessary
if ( s.length > 0 )
{
// We've already added an item, so add the comma separator
s += ","
}
s += escapeString( v.@name.toString() ) + ":"
+ convertToString( o[ v.@name ] );
}
return s;
}