2 Copyright (c) 2008, Adobe Systems Incorporated
\r
5 Redistribution and use in source and binary forms, with or without
\r
6 modification, are permitted provided that the following conditions are
\r
9 * Redistributions of source code must retain the above copyright notice,
\r
10 this list of conditions and the following disclaimer.
\r
12 * Redistributions in binary form must reproduce the above copyright
\r
13 notice, this list of conditions and the following disclaimer in the
\r
14 documentation and/or other materials provided with the distribution.
\r
16 * Neither the name of Adobe Systems Incorporated nor the names of its
\r
17 contributors may be used to endorse or promote products derived from
\r
18 this software without specific prior written permission.
\r
20 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
\r
21 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
\r
22 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
\r
23 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
\r
24 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
\r
25 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
\r
26 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
\r
27 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
\r
28 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
\r
29 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
\r
30 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\r
33 package com.adobe.serialization.json
\r
36 import flash.utils.describeType;
\r
38 public class JSONEncoder {
\r
40 /** The string that is going to represent the object we're encoding */
\r
41 private var jsonString:String;
\r
44 * Creates a new JSONEncoder.
\r
46 * @param o The object to encode as a JSON string
\r
47 * @langversion ActionScript 3.0
\r
48 * @playerversion Flash 9.0
\r
51 public function JSONEncoder( value:* ) {
\r
52 jsonString = convertToString( value );
\r
57 * Gets the JSON string from the encoder.
\r
59 * @return The JSON string representation of the object
\r
60 * that was passed to the constructor
\r
61 * @langversion ActionScript 3.0
\r
62 * @playerversion Flash 9.0
\r
65 public function getString():String {
\r
70 * Converts a value to it's JSON string equivalent.
\r
72 * @param value The value to convert. Could be any
\r
73 * type (object, number, array, etc)
\r
75 private function convertToString( value:* ):String {
\r
77 // determine what value is and convert it based on it's type
\r
78 if ( value is String ) {
\r
80 // escape the string so it's formatted correctly
\r
81 return escapeString( value as String );
\r
83 } else if ( value is Number ) {
\r
85 // only encode numbers that finate
\r
86 return isFinite( value as Number) ? value.toString() : "null";
\r
88 } else if ( value is Boolean ) {
\r
90 // convert boolean to string easily
\r
91 return value ? "true" : "false";
\r
93 } else if ( value is Array ) {
\r
95 // call the helper method to convert an array
\r
96 return arrayToString( value as Array );
\r
98 } else if ( value is Object && value != null ) {
\r
100 // call the helper method to convert an object
\r
101 return objectToString( value );
\r
107 * Escapes a string accoding to the JSON specification.
\r
109 * @param str The string to be escaped
\r
110 * @return The string with escaped special characters
\r
111 * according to the JSON specification
\r
113 private function escapeString( str:String ):String {
\r
114 // create a string to store the string's jsonstring value
\r
116 // current character in the string we're processing
\r
118 // store the length in a local variable to reduce lookups
\r
119 var len:Number = str.length;
\r
121 // loop over all of the characters in the string
\r
122 for ( var i:int = 0; i < len; i++ ) {
\r
124 // examine the character to determine if we have to escape it
\r
125 ch = str.charAt( i );
\r
128 case '"': // quotation mark
\r
132 //case '/': // solidus
\r
136 case '\\': // reverse solidus
\r
144 case '\f': // form feed
\r
148 case '\n': // newline
\r
152 case '\r': // carriage return
\r
156 case '\t': // horizontal tab
\r
160 default: // everything else
\r
162 // check for a control character and escape as unicode
\r
164 // get the hex digit(s) of the character (either 1 or 2 digits)
\r
165 var hexCode:String = ch.charCodeAt( 0 ).toString( 16 );
\r
167 // ensure that there are 4 digits by adjusting
\r
168 // the # of zeros accordingly.
\r
169 var zeroPad:String = hexCode.length == 2 ? "00" : "000";
\r
171 // create the unicode escape sequence with 4 hex digits
\r
172 s += "\\u" + zeroPad + hexCode;
\r
175 // no need to do any special encoding, just pass-through
\r
183 return "\"" + s + "\"";
\r
187 * Converts an array to it's JSON string equivalent
\r
189 * @param a The array to convert
\r
190 * @return The JSON string representation of <code>a</code>
\r
192 private function arrayToString( a:Array ):String {
\r
193 // create a string to store the array's jsonstring value
\r
196 // loop over the elements in the array and add their converted
\r
197 // values to the string
\r
198 for ( var i:int = 0; i < a.length; i++ ) {
\r
199 // when the length is 0 we're adding the first element so
\r
200 // no comma is necessary
\r
201 if ( s.length > 0 ) {
\r
202 // we've already added an element, so add the comma separator
\r
206 // convert the value to a string
\r
207 s += convertToString( a[i] );
\r
210 // KNOWN ISSUE: In ActionScript, Arrays can also be associative
\r
211 // objects and you can put anything in them, ie:
\r
212 // myArray["foo"] = "bar";
\r
214 // These properties aren't picked up in the for loop above because
\r
215 // the properties don't correspond to indexes. However, we're
\r
216 // sort of out luck because the JSON specification doesn't allow
\r
217 // these types of array properties.
\r
219 // So, if the array was also used as an associative object, there
\r
220 // may be some values in the array that don't get properly encoded.
\r
222 // A possible solution is to instead encode the Array as an Object
\r
223 // but then it won't get decoded correctly (and won't be an
\r
226 // close the array and return it's string value
\r
227 return "[" + s + "]";
\r
231 * Converts an object to it's JSON string equivalent
\r
233 * @param o The object to convert
\r
234 * @return The JSON string representation of <code>o</code>
\r
236 private function objectToString( o:Object ):String
\r
238 // create a string to store the object's jsonstring value
\r
241 // determine if o is a class instance or a plain object
\r
242 var classInfo:XML = describeType( o );
\r
243 if ( classInfo.@name.toString() == "Object" )
\r
245 // the value of o[key] in the loop below - store this
\r
246 // as a variable so we don't have to keep looking up o[key]
\r
247 // when testing for valid values to convert
\r
250 // loop over the keys in the object and add their converted
\r
251 // values to the string
\r
252 for ( var key:String in o )
\r
254 // assign value to a variable for quick lookup
\r
257 // don't add function's to the JSON string
\r
258 if ( value is Function )
\r
260 // skip this key and try another
\r
264 // when the length is 0 we're adding the first item so
\r
265 // no comma is necessary
\r
266 if ( s.length > 0 ) {
\r
267 // we've already added an item, so add the comma separator
\r
271 s += escapeString( key ) + ":" + convertToString( value );
\r
274 else // o is a class instance
\r
276 // Loop over all of the variables and accessors in the class and
\r
277 // serialize them along with their values.
\r
278 for each ( var v:XML in classInfo..*.( name() == "variable" || name() == "accessor" ) )
\r
280 // When the length is 0 we're adding the first item so
\r
281 // no comma is necessary
\r
282 if ( s.length > 0 ) {
\r
283 // We've already added an item, so add the comma separator
\r
287 s += escapeString( v.@name.toString() ) + ":"
\r
288 + convertToString( o[ v.@name ] );
\r
293 return "{" + s + "}";
\r