Update mcs/class/System.Core/System/TimeZoneInfo.cs
[mono.git] / mcs / class / System.Web.Extensions / System.Web.Script.Serialization / JavaScriptSerializer.cs
1 //
2 // JavaScriptSerializer.cs
3 //
4 // Authors:
5 //   Konstantin Triger <kostat@mainsoft.com>
6 //   Marek Safar <marek.safar@gmail.com>
7 //
8 // (C) 2007 Mainsoft, Inc.  http://www.mainsoft.com
9 // Copyright 2012 Xamarin Inc.
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.Collections.Generic;
33 using System.Text;
34 using Newtonsoft.Json;
35 using System.IO;
36 using System.Collections;
37 using System.Reflection;
38 using Newtonsoft.Json.Utilities;
39 using System.ComponentModel;
40 using System.Configuration;
41 using System.Web.Configuration;
42
43 namespace System.Web.Script.Serialization
44 {
45         public class JavaScriptSerializer
46         {
47                 internal const string SerializedTypeNameKey = "__type";
48                 
49                 List<IEnumerable<JavaScriptConverter>> _converterList;
50                 int _maxJsonLength;
51                 int _recursionLimit;
52                 JavaScriptTypeResolver _typeResolver;
53                 internal static readonly JavaScriptSerializer DefaultSerializer = new JavaScriptSerializer (null, false);
54
55                 public JavaScriptSerializer () : this (null, false)
56                 {
57                 }
58
59                 public JavaScriptSerializer (JavaScriptTypeResolver resolver) : this (resolver, false)
60                 {
61                 }
62                 
63                 internal JavaScriptSerializer (JavaScriptTypeResolver resolver, bool registerConverters)
64                 {
65                         _typeResolver = resolver;
66
67                         ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection) ConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/jsonSerialization");
68                         if (section == null) {
69 #if NET_3_5
70                                 _maxJsonLength = 2097152;
71 #else
72                                 _maxJsonLength = 102400;
73 #endif
74                                 _recursionLimit = 100;
75                         } else {
76                                 _maxJsonLength = section.MaxJsonLength;
77                                 _recursionLimit = section.RecursionLimit;
78
79                                 if (registerConverters) {
80                                         ConvertersCollection converters = section.Converters;
81                                         if (converters != null && converters.Count > 0) {
82                                                 var cvtlist = new List <JavaScriptConverter> ();
83                                                 Type type;
84                                                 string typeName;
85                                                 JavaScriptConverter jsc;
86                                                 
87                                                 foreach (Converter cvt in converters) {
88                                                         typeName = cvt != null ? cvt.Type : null;
89                                                         if (typeName == null)
90                                                                 continue;
91                                                         
92                                                         type = HttpApplication.LoadType (typeName, true);
93                                                         if (type == null || !typeof (JavaScriptConverter).IsAssignableFrom (type))
94                                                                 continue;
95                                                         
96                                                         jsc = Activator.CreateInstance (type) as JavaScriptConverter;
97                                                         cvtlist.Add (jsc);
98                                                 }
99                                         
100                                                 RegisterConverters (cvtlist);
101                                         }
102                                 }
103                         }
104                 }
105
106                 
107                 public int MaxJsonLength {
108                         get {
109                                 return _maxJsonLength;
110                         }
111                         set {
112                                 _maxJsonLength = value;
113                         }
114                 }
115                 
116                 public int RecursionLimit {
117                         get {
118                                 return _recursionLimit;
119                         }
120                         set {
121                                 _recursionLimit = value;
122                         }
123                 }
124
125                 internal JavaScriptTypeResolver TypeResolver {
126                         get { return _typeResolver; }
127                 }
128                 
129                 public T ConvertToType<T> (object obj) {
130                         if (obj == null)
131                                 return default (T);
132
133                         return (T) ConvertToType (obj, typeof (T));
134                 }
135
136 #if NET_4_0
137                 public
138 #else
139                 internal
140 #endif
141                 object ConvertToType (object obj, Type targetType)
142                 {
143                         if (obj == null)
144                                 return null;
145
146                         if (obj is IDictionary<string, object>) {
147                                 if (targetType == null)
148                                         obj = EvaluateDictionary ((IDictionary<string, object>) obj);
149                                 else {
150                                         JavaScriptConverter converter = GetConverter (targetType);
151                                         if (converter != null)
152                                                 return converter.Deserialize (
153                                                         EvaluateDictionary ((IDictionary<string, object>) obj),
154                                                         targetType, this);
155                                 }
156
157                                 return ConvertToObject ((IDictionary<string, object>) obj, targetType);
158                         }
159                         if (obj is ArrayList)
160                                 return ConvertToList ((ArrayList) obj, targetType);
161
162                         if (targetType == null)
163                                 return obj;
164
165                         Type sourceType = obj.GetType ();
166                         if (targetType.IsAssignableFrom (sourceType))
167                                 return obj;
168
169                         if (targetType.IsEnum)
170                                 if (obj is string)
171                                         return Enum.Parse (targetType, (string) obj, true);
172                                 else
173                                         return Enum.ToObject (targetType, obj);
174
175                         TypeConverter c = TypeDescriptor.GetConverter (targetType);
176                         if (c.CanConvertFrom (sourceType)) {
177                                 if (obj is string)
178                                         return c.ConvertFromInvariantString ((string) obj);
179
180                                 return c.ConvertFrom (obj);
181                         }
182
183                         /*
184                          * Take care of the special case whereas in JSON an empty string ("") really means 
185                          * an empty value 
186                          * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
187                          */
188                         if ((targetType.IsGenericType) && (targetType.GetGenericTypeDefinition() == typeof(Nullable<>)))
189                         {
190                                 string s = obj as String;
191                                 if (String.IsNullOrEmpty(s))
192                                                 return null;
193                         }
194
195                         return Convert.ChangeType (obj, targetType);
196                 }
197
198                 public T Deserialize<T> (string input) {
199                         return ConvertToType<T> (DeserializeObjectInternal(input));
200                 }
201
202                 static object Evaluate (object value) {
203                         return Evaluate (value, false);
204                 }
205
206                 static object Evaluate (object value, bool convertListToArray) {
207                         if (value is IDictionary<string, object>)
208                                 value = EvaluateDictionary ((IDictionary<string, object>) value, convertListToArray);
209                         else if (value is ArrayList)
210                                 value = EvaluateList ((ArrayList) value, convertListToArray);
211                         return value;
212                 }
213
214                 static object EvaluateList (ArrayList e) {
215                         return EvaluateList (e, false);
216                 }
217
218                 static object EvaluateList (ArrayList e, bool convertListToArray) {
219                         ArrayList list = new ArrayList ();
220                         foreach (object value in e)
221                                 list.Add (Evaluate (value, convertListToArray));
222
223                         return convertListToArray ? (object) list.ToArray () : list;
224                 }
225
226                 static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
227                         return EvaluateDictionary (dict, false);
228                 }
229
230                 static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict, bool convertListToArray) {
231                         Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
232                         foreach (KeyValuePair<string, object> entry in dict) {
233                                 d.Add (entry.Key, Evaluate (entry.Value, convertListToArray));
234                         }
235
236                         return d;
237                 }
238
239                 static readonly Type typeofObject = typeof(object);
240                 static readonly Type typeofGenList = typeof (List<>);
241
242                 object ConvertToList (ArrayList col, Type type) {
243                         Type elementType = null;
244                         if (type != null && type.HasElementType)
245                                 elementType = type.GetElementType ();
246
247                         IList list;
248                         if (type == null || type.IsArray || typeofObject == type || typeof (ArrayList).IsAssignableFrom (type))
249                                 list = new ArrayList ();
250                         else if (ReflectionUtils.IsInstantiatableType (type))
251                                 // non-generic typed list
252                                 list = (IList) Activator.CreateInstance (type, true);
253                         else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
254                                 if (type.IsGenericType) {
255                                         Type [] genArgs = type.GetGenericArguments ();
256                                         elementType = genArgs [0];
257                                         // generic list
258                                         list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
259                                 } else
260                                         list = new ArrayList ();
261                         } else
262                                 throw new InvalidOperationException (String.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
263
264                         if (list.IsReadOnly) {
265                                 EvaluateList (col);
266                                 return list;
267                         }
268
269                         foreach (object value in col)
270                                 list.Add (ConvertToType (value, elementType));
271
272                         if (type != null && type.IsArray)
273                                 list = ((ArrayList) list).ToArray (elementType);
274
275                         return list;
276                 }
277
278                 object ConvertToObject (IDictionary<string, object> dict, Type type) 
279                 {
280                         if (_typeResolver != null) {
281                                 if (dict.Keys.Contains(SerializedTypeNameKey)) {
282                                         // already Evaluated
283                                         type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
284                                 }
285                         }
286
287                         if (type.IsGenericType) {
288                                 if (type.GetGenericTypeDefinition ().IsAssignableFrom (typeof (IDictionary <,>))) {
289                                         Type[] arguments = type.GetGenericArguments ();
290                                         if (arguments == null || arguments.Length != 2 || (arguments [0] != typeof (object) && arguments [0] != typeof (string)))
291                                                 throw new InvalidOperationException (
292                                                         "Type '" + type + "' is not not supported for serialization/deserialization of a dictionary, keys must be strings or objects.");
293                                         if (type.IsAbstract) {
294                                                 Type dictType = typeof (Dictionary <,>);
295                                                 type = dictType.MakeGenericType (arguments [0], arguments [1]);
296                                         }
297                                 }
298                         } else if (type.IsAssignableFrom (typeof (IDictionary)))
299                                 type = typeof (Dictionary <string, object>);
300                         
301                         object target = Activator.CreateInstance (type, true);
302
303                         foreach (KeyValuePair<string, object> entry in dict) {
304                                 object value = entry.Value;
305                                 if (target is IDictionary) {
306                                         Type valueType = ReflectionUtils.GetTypedDictionaryValueType (type);
307                                         if (value != null && valueType == typeof (System.Object))
308                                                 valueType = value.GetType ();
309                                         
310                                         ((IDictionary) target).Add (entry.Key, ConvertToType (value, valueType));
311                                         continue;
312                                 }
313                                 MemberInfo [] memberCollection = type.GetMember (entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
314                                 if (memberCollection == null || memberCollection.Length == 0) {
315                                         //must evaluate value
316                                         Evaluate (value);
317                                         continue;
318                                 }
319
320                                 MemberInfo member = memberCollection [0];
321
322                                 if (!ReflectionUtils.CanSetMemberValue (member)) {
323                                         //must evaluate value
324                                         Evaluate (value);
325                                         continue;
326                                 }
327
328                                 Type memberType = ReflectionUtils.GetMemberUnderlyingType (member);
329
330                                 if (memberType.IsInterface) {
331                                         if (memberType.IsGenericType)
332                                                 memberType = ResolveGenericInterfaceToType (memberType);
333                                         else
334                                                 memberType = ResolveInterfaceToType (memberType);
335
336                                         if (memberType == null)
337                                                 throw new InvalidOperationException ("Unable to deserialize a member, as its type is an unknown interface.");
338                                 }
339                                 
340                                 ReflectionUtils.SetMemberValue (member, target, ConvertToType(value, memberType));
341                         }
342
343                         return target;
344                 }
345
346                 Type ResolveGenericInterfaceToType (Type type)
347                 {
348                         Type[] genericArgs = type.GetGenericArguments ();
349                         
350                         if (ReflectionUtils.IsSubClass (type, typeof (IDictionary <,>)))
351                                 return typeof (Dictionary <,>).MakeGenericType (genericArgs);
352
353                         if (ReflectionUtils.IsSubClass (type, typeof (IList <>)) ||
354                             ReflectionUtils.IsSubClass (type, typeof (ICollection <>)) ||
355                             ReflectionUtils.IsSubClass (type, typeof (IEnumerable <>))
356                         )
357                                 return typeof (List <>).MakeGenericType (genericArgs);
358
359                         if (ReflectionUtils.IsSubClass (type, typeof (IComparer <>)))
360                                 return typeof (Comparer <>).MakeGenericType (genericArgs);
361
362                         if (ReflectionUtils.IsSubClass (type, typeof (IEqualityComparer <>)))
363                                 return typeof (EqualityComparer <>).MakeGenericType (genericArgs);
364
365                         return null;
366                 }
367
368                 Type ResolveInterfaceToType (Type type)
369                 {
370                         if (typeof (IDictionary).IsAssignableFrom (type))
371                                 return typeof (Hashtable);
372
373                         if (typeof (IList).IsAssignableFrom (type) ||
374                             typeof (ICollection).IsAssignableFrom (type) ||
375                             typeof (IEnumerable).IsAssignableFrom (type))
376                                 return typeof (ArrayList);
377
378                         if (typeof (IComparer).IsAssignableFrom (type))
379                                 return typeof (Comparer);
380
381                         return null;
382                 }
383                 
384                 public object DeserializeObject (string input) {
385                         object obj = Evaluate (DeserializeObjectInternal (input), true);
386                         IDictionary dictObj = obj as IDictionary;
387                         if (dictObj != null && dictObj.Contains(SerializedTypeNameKey)){
388                                 if (_typeResolver == null) {
389                                         throw new ArgumentNullException ("resolver", "Must have a type resolver to deserialize an object that has an '__type' member");
390                                 }
391
392                                 obj = ConvertToType(obj, null);
393                         }
394                         return obj; 
395                 }
396
397                 internal object DeserializeObjectInternal (string input) {
398                         return Json.Deserialize (input, this);
399                 }
400
401                 internal object DeserializeObjectInternal (TextReader input) {
402                         return Json.Deserialize (input, this);
403                 }
404
405                 public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
406                         if (converters == null)
407                                 throw new ArgumentNullException ("converters");
408
409                         if (_converterList == null)
410                                 _converterList = new List<IEnumerable<JavaScriptConverter>> ();
411                         _converterList.Add (converters);
412                 }
413
414                 internal JavaScriptConverter GetConverter (Type type) {
415                         if (_converterList != null)
416                                 for (int i = 0; i < _converterList.Count; i++) {
417                                         foreach (JavaScriptConverter converter in _converterList [i])
418                                                 foreach (Type supportedType in converter.SupportedTypes)
419                                                         if (supportedType.IsAssignableFrom (type))
420                                                                 return converter;
421                                 }
422
423                         return null;
424                 }
425
426                 public string Serialize (object obj) {
427                         StringBuilder b = new StringBuilder ();
428                         Serialize (obj, b);
429                         return b.ToString ();
430                 }
431
432                 public void Serialize (object obj, StringBuilder output) {
433                         Json.Serialize (obj, this, output);
434                 }
435
436                 internal void Serialize (object obj, TextWriter output) {
437                         Json.Serialize (obj, this, output);
438                 }
439         }
440 }