2 // JavaScriptSerializer.cs
5 // Konstantin Triger <kostat@mainsoft.com>
6 // Marek Safar <marek.safar@gmail.com>
8 // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
9 // Copyright 2012 Xamarin Inc.
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections.Generic;
34 using Newtonsoft.Json;
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;
43 namespace System.Web.Script.Serialization
45 public class JavaScriptSerializer
47 internal const string SerializedTypeNameKey = "__type";
49 List<IEnumerable<JavaScriptConverter>> _converterList;
52 JavaScriptTypeResolver _typeResolver;
53 internal static readonly JavaScriptSerializer DefaultSerializer = new JavaScriptSerializer (null, false);
55 public JavaScriptSerializer () : this (null, false)
59 public JavaScriptSerializer (JavaScriptTypeResolver resolver) : this (resolver, false)
63 internal JavaScriptSerializer (JavaScriptTypeResolver resolver, bool registerConverters)
65 _typeResolver = resolver;
67 ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection) ConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/jsonSerialization");
68 if (section == null) {
70 _maxJsonLength = 2097152;
72 _maxJsonLength = 102400;
74 _recursionLimit = 100;
76 _maxJsonLength = section.MaxJsonLength;
77 _recursionLimit = section.RecursionLimit;
79 if (registerConverters) {
80 ConvertersCollection converters = section.Converters;
81 if (converters != null && converters.Count > 0) {
82 var cvtlist = new List <JavaScriptConverter> ();
85 JavaScriptConverter jsc;
87 foreach (Converter cvt in converters) {
88 typeName = cvt != null ? cvt.Type : null;
92 type = HttpApplication.LoadType (typeName, true);
93 if (type == null || !typeof (JavaScriptConverter).IsAssignableFrom (type))
96 jsc = Activator.CreateInstance (type) as JavaScriptConverter;
100 RegisterConverters (cvtlist);
107 public int MaxJsonLength {
109 return _maxJsonLength;
112 _maxJsonLength = value;
116 public int RecursionLimit {
118 return _recursionLimit;
121 _recursionLimit = value;
125 internal JavaScriptTypeResolver TypeResolver {
126 get { return _typeResolver; }
129 public T ConvertToType<T> (object obj) {
133 return (T) ConvertToType (obj, typeof (T));
141 object ConvertToType (object obj, Type targetType)
146 if (obj is IDictionary<string, object>) {
147 if (targetType == null)
148 obj = EvaluateDictionary ((IDictionary<string, object>) obj);
150 JavaScriptConverter converter = GetConverter (targetType);
151 if (converter != null)
152 return converter.Deserialize (
153 EvaluateDictionary ((IDictionary<string, object>) obj),
157 return ConvertToObject ((IDictionary<string, object>) obj, targetType);
159 if (obj is ArrayList)
160 return ConvertToList ((ArrayList) obj, targetType);
162 if (targetType == null)
165 Type sourceType = obj.GetType ();
166 if (targetType.IsAssignableFrom (sourceType))
169 if (targetType.IsEnum)
171 return Enum.Parse (targetType, (string) obj, true);
173 return Enum.ToObject (targetType, obj);
175 TypeConverter c = TypeDescriptor.GetConverter (targetType);
176 if (c.CanConvertFrom (sourceType)) {
178 return c.ConvertFromInvariantString ((string) obj);
180 return c.ConvertFrom (obj);
184 * Take care of the special case whereas in JSON an empty string ("") really means
186 * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
188 if ((targetType.IsGenericType) && (targetType.GetGenericTypeDefinition() == typeof(Nullable<>)))
190 string s = obj as String;
191 if (String.IsNullOrEmpty(s))
195 return Convert.ChangeType (obj, targetType);
198 public T Deserialize<T> (string input) {
199 return ConvertToType<T> (DeserializeObjectInternal(input));
202 static object Evaluate (object value) {
203 return Evaluate (value, false);
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);
214 static object EvaluateList (ArrayList e) {
215 return EvaluateList (e, false);
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));
223 return convertListToArray ? (object) list.ToArray () : list;
226 static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
227 return EvaluateDictionary (dict, false);
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));
239 static readonly Type typeofObject = typeof(object);
240 static readonly Type typeofGenList = typeof (List<>);
242 object ConvertToList (ArrayList col, Type type) {
243 Type elementType = null;
244 if (type != null && type.HasElementType)
245 elementType = type.GetElementType ();
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];
258 list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
260 list = new ArrayList ();
262 throw new InvalidOperationException (String.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
264 if (list.IsReadOnly) {
269 foreach (object value in col)
270 list.Add (ConvertToType (value, elementType));
272 if (type != null && type.IsArray)
273 list = ((ArrayList) list).ToArray (elementType);
278 object ConvertToObject (IDictionary<string, object> dict, Type type)
280 if (_typeResolver != null) {
281 if (dict.Keys.Contains(SerializedTypeNameKey)) {
283 type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
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]);
298 } else if (type.IsAssignableFrom (typeof (IDictionary)))
299 type = typeof (Dictionary <string, object>);
301 object target = Activator.CreateInstance (type, true);
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 ();
310 ((IDictionary) target).Add (entry.Key, ConvertToType (value, valueType));
313 MemberInfo [] memberCollection = type.GetMember (entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
314 if (memberCollection == null || memberCollection.Length == 0) {
315 //must evaluate value
320 MemberInfo member = memberCollection [0];
322 if (!ReflectionUtils.CanSetMemberValue (member)) {
323 //must evaluate value
328 Type memberType = ReflectionUtils.GetMemberUnderlyingType (member);
330 if (memberType.IsInterface) {
331 if (memberType.IsGenericType)
332 memberType = ResolveGenericInterfaceToType (memberType);
334 memberType = ResolveInterfaceToType (memberType);
336 if (memberType == null)
337 throw new InvalidOperationException ("Unable to deserialize a member, as its type is an unknown interface.");
340 ReflectionUtils.SetMemberValue (member, target, ConvertToType(value, memberType));
346 Type ResolveGenericInterfaceToType (Type type)
348 Type[] genericArgs = type.GetGenericArguments ();
350 if (ReflectionUtils.IsSubClass (type, typeof (IDictionary <,>)))
351 return typeof (Dictionary <,>).MakeGenericType (genericArgs);
353 if (ReflectionUtils.IsSubClass (type, typeof (IList <>)) ||
354 ReflectionUtils.IsSubClass (type, typeof (ICollection <>)) ||
355 ReflectionUtils.IsSubClass (type, typeof (IEnumerable <>))
357 return typeof (List <>).MakeGenericType (genericArgs);
359 if (ReflectionUtils.IsSubClass (type, typeof (IComparer <>)))
360 return typeof (Comparer <>).MakeGenericType (genericArgs);
362 if (ReflectionUtils.IsSubClass (type, typeof (IEqualityComparer <>)))
363 return typeof (EqualityComparer <>).MakeGenericType (genericArgs);
368 Type ResolveInterfaceToType (Type type)
370 if (typeof (IDictionary).IsAssignableFrom (type))
371 return typeof (Hashtable);
373 if (typeof (IList).IsAssignableFrom (type) ||
374 typeof (ICollection).IsAssignableFrom (type) ||
375 typeof (IEnumerable).IsAssignableFrom (type))
376 return typeof (ArrayList);
378 if (typeof (IComparer).IsAssignableFrom (type))
379 return typeof (Comparer);
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");
392 obj = ConvertToType(obj, null);
397 internal object DeserializeObjectInternal (string input) {
398 return Json.Deserialize (input, this);
401 internal object DeserializeObjectInternal (TextReader input) {
402 return Json.Deserialize (input, this);
405 public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
406 if (converters == null)
407 throw new ArgumentNullException ("converters");
409 if (_converterList == null)
410 _converterList = new List<IEnumerable<JavaScriptConverter>> ();
411 _converterList.Add (converters);
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))
426 public string Serialize (object obj) {
427 StringBuilder b = new StringBuilder ();
429 return b.ToString ();
432 public void Serialize (object obj, StringBuilder output) {
433 Json.Serialize (obj, this, output);
436 internal void Serialize (object obj, TextWriter output) {
437 Json.Serialize (obj, this, output);