[MWF] Improve ellipsis handling
[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                         if ((targetType.IsGenericType) && (targetType.GetGenericTypeDefinition () == typeof (Nullable<>))) {
184                                 if (obj is String) {
185                                         /*
186                                          * Take care of the special case whereas in JSON an empty string ("") really means 
187                                          * an empty value 
188                                          * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
189                                          */
190                                         if(String.IsNullOrEmpty ((String)obj))
191                                                 return null;
192                                 } else if (c.CanConvertFrom (typeof (string))) {
193                                         TypeConverter objConverter = TypeDescriptor.GetConverter (obj);
194                                         string s = objConverter.ConvertToInvariantString (obj);
195                                         return c.ConvertFromInvariantString (s);
196                                 }
197                         }
198
199                         return Convert.ChangeType (obj, targetType);
200                 }
201
202                 public T Deserialize<T> (string input) {
203                         return ConvertToType<T> (DeserializeObjectInternal(input));
204                 }
205
206                 public object Deserialize (string input, Type targetType) {
207                         return DeserializeObjectInternal (input);
208                 }
209
210                 static object Evaluate (object value) {
211                         return Evaluate (value, false);
212                 }
213
214                 static object Evaluate (object value, bool convertListToArray) {
215                         if (value is IDictionary<string, object>)
216                                 value = EvaluateDictionary ((IDictionary<string, object>) value, convertListToArray);
217                         else if (value is ArrayList)
218                                 value = EvaluateList ((ArrayList) value, convertListToArray);
219                         return value;
220                 }
221
222                 static object EvaluateList (ArrayList e) {
223                         return EvaluateList (e, false);
224                 }
225
226                 static object EvaluateList (ArrayList e, bool convertListToArray) {
227                         ArrayList list = new ArrayList ();
228                         foreach (object value in e)
229                                 list.Add (Evaluate (value, convertListToArray));
230
231                         return convertListToArray ? (object) list.ToArray () : list;
232                 }
233
234                 static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
235                         return EvaluateDictionary (dict, false);
236                 }
237
238                 static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict, bool convertListToArray) {
239                         Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
240                         foreach (KeyValuePair<string, object> entry in dict) {
241                                 d.Add (entry.Key, Evaluate (entry.Value, convertListToArray));
242                         }
243
244                         return d;
245                 }
246
247                 static readonly Type typeofObject = typeof(object);
248                 static readonly Type typeofGenList = typeof (List<>);
249
250                 object ConvertToList (ArrayList col, Type type) {
251                         Type elementType = null;
252                         if (type != null && type.HasElementType)
253                                 elementType = type.GetElementType ();
254
255                         IList list;
256                         if (type == null || type.IsArray || typeofObject == type || typeof (ArrayList).IsAssignableFrom (type))
257                                 list = new ArrayList ();
258                         else if (ReflectionUtils.IsInstantiatableType (type))
259                                 // non-generic typed list
260                                 list = (IList) Activator.CreateInstance (type, true);
261                         else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
262                                 if (type.IsGenericType) {
263                                         Type [] genArgs = type.GetGenericArguments ();
264                                         elementType = genArgs [0];
265                                         // generic list
266                                         list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
267                                 } else
268                                         list = new ArrayList ();
269                         } else
270                                 throw new InvalidOperationException (String.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
271
272                         if (list.IsReadOnly) {
273                                 EvaluateList (col);
274                                 return list;
275                         }
276                         
277                         if (elementType == null)
278                                 elementType = typeof (object);
279
280                         foreach (object value in col)
281                                 list.Add (ConvertToType (value, elementType));
282
283                         if (type != null && type.IsArray)
284                                 list = ((ArrayList) list).ToArray (elementType);
285
286                         return list;
287                 }
288
289                 object ConvertToObject (IDictionary<string, object> dict, Type type) 
290                 {
291                         if (_typeResolver != null) {
292                                 if (dict.Keys.Contains(SerializedTypeNameKey)) {
293                                         // already Evaluated
294                                         type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
295                                 }
296                         }
297
298                         if (type.IsGenericType) {
299                                 if (type.GetGenericTypeDefinition ().IsAssignableFrom (typeof (IDictionary <,>))) {
300                                         Type[] arguments = type.GetGenericArguments ();
301                                         if (arguments == null || arguments.Length != 2 || (arguments [0] != typeof (object) && arguments [0] != typeof (string)))
302                                                 throw new InvalidOperationException (
303                                                         "Type '" + type + "' is not not supported for serialization/deserialization of a dictionary, keys must be strings or objects.");
304                                         if (type.IsAbstract) {
305                                                 Type dictType = typeof (Dictionary <,>);
306                                                 type = dictType.MakeGenericType (arguments [0], arguments [1]);
307                                         }
308                                 }
309                         } else if (type.IsAssignableFrom (typeof (IDictionary)))
310                                 type = typeof (Dictionary <string, object>);
311                         
312                         object target = Activator.CreateInstance (type, true);
313
314                         foreach (KeyValuePair<string, object> entry in dict) {
315                                 object value = entry.Value;
316                                 if (target is IDictionary) {
317                                         Type valueType = ReflectionUtils.GetTypedDictionaryValueType (type);
318                                         if (value != null && valueType == typeof (System.Object))
319                                                 valueType = value.GetType ();
320                                         
321                                         ((IDictionary) target).Add (entry.Key, ConvertToType (value, valueType));
322                                         continue;
323                                 }
324                                 MemberInfo [] memberCollection = type.GetMember (entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
325                                 if (memberCollection == null || memberCollection.Length == 0) {
326                                         //must evaluate value
327                                         Evaluate (value);
328                                         continue;
329                                 }
330
331                                 MemberInfo member = memberCollection [0];
332
333                                 if (!ReflectionUtils.CanSetMemberValue (member)) {
334                                         //must evaluate value
335                                         Evaluate (value);
336                                         continue;
337                                 }
338
339                                 Type memberType = ReflectionUtils.GetMemberUnderlyingType (member);
340
341                                 if (memberType.IsInterface) {
342                                         if (memberType.IsGenericType)
343                                                 memberType = ResolveGenericInterfaceToType (memberType);
344                                         else
345                                                 memberType = ResolveInterfaceToType (memberType);
346
347                                         if (memberType == null)
348                                                 throw new InvalidOperationException ("Unable to deserialize a member, as its type is an unknown interface.");
349                                 }
350                                 
351                                 ReflectionUtils.SetMemberValue (member, target, ConvertToType(value, memberType));
352                         }
353
354                         return target;
355                 }
356
357                 Type ResolveGenericInterfaceToType (Type type)
358                 {
359                         Type[] genericArgs = type.GetGenericArguments ();
360                         
361                         if (ReflectionUtils.IsSubClass (type, typeof (IDictionary <,>)))
362                                 return typeof (Dictionary <,>).MakeGenericType (genericArgs);
363
364                         if (ReflectionUtils.IsSubClass (type, typeof (IList <>)) ||
365                             ReflectionUtils.IsSubClass (type, typeof (ICollection <>)) ||
366                             ReflectionUtils.IsSubClass (type, typeof (IEnumerable <>))
367                         )
368                                 return typeof (List <>).MakeGenericType (genericArgs);
369
370                         if (ReflectionUtils.IsSubClass (type, typeof (IComparer <>)))
371                                 return typeof (Comparer <>).MakeGenericType (genericArgs);
372
373                         if (ReflectionUtils.IsSubClass (type, typeof (IEqualityComparer <>)))
374                                 return typeof (EqualityComparer <>).MakeGenericType (genericArgs);
375
376                         return null;
377                 }
378
379                 Type ResolveInterfaceToType (Type type)
380                 {
381                         if (typeof (IDictionary).IsAssignableFrom (type))
382                                 return typeof (Hashtable);
383
384                         if (typeof (IList).IsAssignableFrom (type) ||
385                             typeof (ICollection).IsAssignableFrom (type) ||
386                             typeof (IEnumerable).IsAssignableFrom (type))
387                                 return typeof (ArrayList);
388
389                         if (typeof (IComparer).IsAssignableFrom (type))
390                                 return typeof (Comparer);
391
392                         return null;
393                 }
394                 
395                 public object DeserializeObject (string input) {
396                         object obj = Evaluate (DeserializeObjectInternal (input), true);
397                         IDictionary dictObj = obj as IDictionary;
398                         if (dictObj != null && dictObj.Contains(SerializedTypeNameKey)){
399                                 if (_typeResolver == null) {
400                                         throw new ArgumentNullException ("resolver", "Must have a type resolver to deserialize an object that has an '__type' member");
401                                 }
402
403                                 obj = ConvertToType(obj, null);
404                         }
405                         return obj; 
406                 }
407
408                 internal object DeserializeObjectInternal (string input) {
409                         return Json.Deserialize (input, this);
410                 }
411
412                 internal object DeserializeObjectInternal (TextReader input) {
413                         return Json.Deserialize (input, this);
414                 }
415
416                 public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
417                         if (converters == null)
418                                 throw new ArgumentNullException ("converters");
419
420                         if (_converterList == null)
421                                 _converterList = new List<IEnumerable<JavaScriptConverter>> ();
422                         _converterList.Add (converters);
423                 }
424
425                 internal JavaScriptConverter GetConverter (Type type) {
426                         if (_converterList != null)
427                                 for (int i = 0; i < _converterList.Count; i++) {
428                                         foreach (JavaScriptConverter converter in _converterList [i])
429                                                 foreach (Type supportedType in converter.SupportedTypes)
430                                                         if (supportedType.IsAssignableFrom (type))
431                                                                 return converter;
432                                 }
433
434                         return null;
435                 }
436
437                 public string Serialize (object obj) {
438                         StringBuilder b = new StringBuilder ();
439                         Serialize (obj, b);
440                         return b.ToString ();
441                 }
442
443                 public void Serialize (object obj, StringBuilder output) {
444                         Json.Serialize (obj, this, output);
445                 }
446
447                 internal void Serialize (object obj, TextWriter output) {
448                         Json.Serialize (obj, this, output);
449                 }
450         }
451 }