try to fix some minor dropdown bugs
[potlatch2.git] / com / adobe / serialization / json / JSONEncoder.as
1 /*\r
2   Copyright (c) 2008, Adobe Systems Incorporated\r
3   All rights reserved.\r
4 \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
7   met:\r
8 \r
9   * Redistributions of source code must retain the above copyright notice, \r
10     this list of conditions and the following disclaimer.\r
11   \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
15   \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
19 \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
31 */\r
32 \r
33 package com.adobe.serialization.json \r
34 {\r
35 \r
36         import flash.utils.describeType;\r
37 \r
38         public class JSONEncoder {\r
39         \r
40                 /** The string that is going to represent the object we're encoding */\r
41                 private var jsonString:String;\r
42                 \r
43                 /**\r
44                  * Creates a new JSONEncoder.\r
45                  *\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
49                  * @tiptext\r
50                  */\r
51                 public function JSONEncoder( value:* ) {\r
52                         jsonString = convertToString( value );\r
53                 \r
54                 }\r
55                 \r
56                 /**\r
57                  * Gets the JSON string from the encoder.\r
58                  *\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
63                  * @tiptext\r
64                  */\r
65                 public function getString():String {\r
66                         return jsonString;\r
67                 }\r
68                 \r
69                 /**\r
70                  * Converts a value to it's JSON string equivalent.\r
71                  *\r
72                  * @param value The value to convert.  Could be any \r
73                  *              type (object, number, array, etc)\r
74                  */\r
75                 private function convertToString( value:* ):String {\r
76                         \r
77                         // determine what value is and convert it based on it's type\r
78                         if ( value is String ) {\r
79                                 \r
80                                 // escape the string so it's formatted correctly\r
81                                 return escapeString( value as String );\r
82                                 \r
83                         } else if ( value is Number ) {\r
84                                 \r
85                                 // only encode numbers that finate\r
86                                 return isFinite( value as Number) ? value.toString() : "null";\r
87 \r
88                         } else if ( value is Boolean ) {\r
89                                 \r
90                                 // convert boolean to string easily\r
91                                 return value ? "true" : "false";\r
92 \r
93                         } else if ( value is Array ) {\r
94                         \r
95                                 // call the helper method to convert an array\r
96                                 return arrayToString( value as Array );\r
97                         \r
98                         } else if ( value is Object && value != null ) {\r
99                         \r
100                                 // call the helper method to convert an object\r
101                                 return objectToString( value );\r
102                         }\r
103             return "null";\r
104                 }\r
105                 \r
106                 /**\r
107                  * Escapes a string accoding to the JSON specification.\r
108                  *\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
112                  */\r
113                 private function escapeString( str:String ):String {\r
114                         // create a string to store the string's jsonstring value\r
115                         var s:String = "";\r
116                         // current character in the string we're processing\r
117                         var ch:String;\r
118                         // store the length in a local variable to reduce lookups\r
119                         var len:Number = str.length;\r
120                         \r
121                         // loop over all of the characters in the string\r
122                         for ( var i:int = 0; i < len; i++ ) {\r
123                         \r
124                                 // examine the character to determine if we have to escape it\r
125                                 ch = str.charAt( i );\r
126                                 switch ( ch ) {\r
127                                 \r
128                                         case '"':       // quotation mark\r
129                                                 s += "\\\"";\r
130                                                 break;\r
131                                                 \r
132                                         //case '/':     // solidus\r
133                                         //      s += "\\/";\r
134                                         //      break;\r
135                                                 \r
136                                         case '\\':      // reverse solidus\r
137                                                 s += "\\\\";\r
138                                                 break;\r
139                                                 \r
140                                         case '\b':      // bell\r
141                                                 s += "\\b";\r
142                                                 break;\r
143                                                 \r
144                                         case '\f':      // form feed\r
145                                                 s += "\\f";\r
146                                                 break;\r
147                                                 \r
148                                         case '\n':      // newline\r
149                                                 s += "\\n";\r
150                                                 break;\r
151                                                 \r
152                                         case '\r':      // carriage return\r
153                                                 s += "\\r";\r
154                                                 break;\r
155                                                 \r
156                                         case '\t':      // horizontal tab\r
157                                                 s += "\\t";\r
158                                                 break;\r
159                                                 \r
160                                         default:        // everything else\r
161                                                 \r
162                                                 // check for a control character and escape as unicode\r
163                                                 if ( ch < ' ' ) {\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
166                                                         \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
170                                                         \r
171                                                         // create the unicode escape sequence with 4 hex digits\r
172                                                         s += "\\u" + zeroPad + hexCode;\r
173                                                 } else {\r
174                                                 \r
175                                                         // no need to do any special encoding, just pass-through\r
176                                                         s += ch;\r
177                                                         \r
178                                                 }\r
179                                 }       // end switch\r
180                                 \r
181                         }       // end for loop\r
182                                                 \r
183                         return "\"" + s + "\"";\r
184                 }\r
185                 \r
186                 /**\r
187                  * Converts an array to it's JSON string equivalent\r
188                  *\r
189                  * @param a The array to convert\r
190                  * @return The JSON string representation of <code>a</code>\r
191                  */\r
192                 private function arrayToString( a:Array ):String {\r
193                         // create a string to store the array's jsonstring value\r
194                         var s:String = "";\r
195                         \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
203                                         s += ","\r
204                                 }\r
205                                 \r
206                                 // convert the value to a string\r
207                                 s += convertToString( a[i] );   \r
208                         }\r
209                         \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
213                         //\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
218                         //\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
221                         //\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
224                         // Array instance)\r
225                                                 \r
226                         // close the array and return it's string value\r
227                         return "[" + s + "]";\r
228                 }\r
229                 \r
230                 /**\r
231                  * Converts an object to it's JSON string equivalent\r
232                  *\r
233                  * @param o The object to convert\r
234                  * @return The JSON string representation of <code>o</code>\r
235                  */\r
236                 private function objectToString( o:Object ):String\r
237                 {\r
238                         // create a string to store the object's jsonstring value\r
239                         var s:String = "";\r
240                         \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
244                         {\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
248                                 var value:Object;\r
249                                 \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
253                                 {\r
254                                         // assign value to a variable for quick lookup\r
255                                         value = o[key];\r
256                                         \r
257                                         // don't add function's to the JSON string\r
258                                         if ( value is Function )\r
259                                         {\r
260                                                 // skip this key and try another\r
261                                                 continue;\r
262                                         }\r
263                                         \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
268                                                 s += ","\r
269                                         }\r
270                                         \r
271                                         s += escapeString( key ) + ":" + convertToString( value );\r
272                                 }\r
273                         }\r
274                         else // o is a class instance\r
275                         {\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
279                                 {\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
284                                                 s += ","\r
285                                         }\r
286                                         \r
287                                         s += escapeString( v.@name.toString() ) + ":" \r
288                                                         + convertToString( o[ v.@name ] );\r
289                                 }\r
290                                 \r
291                         }\r
292                         \r
293                         return "{" + s + "}";\r
294                 }\r
295 \r
296                 \r
297         }\r
298         \r
299 }\r