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);
183 if ((targetType.IsGenericType) && (targetType.GetGenericTypeDefinition () == typeof (Nullable<>))) {
186 * Take care of the special case whereas in JSON an empty string ("") really means
188 * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
190 if(String.IsNullOrEmpty ((String)obj))
192 } else if (c.CanConvertFrom (typeof (string))) {
193 TypeConverter objConverter = TypeDescriptor.GetConverter (obj);
194 string s = objConverter.ConvertToInvariantString (obj);
195 return c.ConvertFromInvariantString (s);
199 return Convert.ChangeType (obj, targetType);
202 public T Deserialize<T> (string input) {
203 return ConvertToType<T> (DeserializeObjectInternal(input));
206 public object Deserialize (string input, Type targetType) {
207 return DeserializeObjectInternal (input);
210 static object Evaluate (object value) {
211 return Evaluate (value, false);
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);
222 static object EvaluateList (ArrayList e) {
223 return EvaluateList (e, false);
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));
231 return convertListToArray ? (object) list.ToArray () : list;
234 static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
235 return EvaluateDictionary (dict, false);
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));
247 static readonly Type typeofObject = typeof(object);
248 static readonly Type typeofGenList = typeof (List<>);
250 object ConvertToList (ArrayList col, Type type) {
251 Type elementType = null;
252 if (type != null && type.HasElementType)
253 elementType = type.GetElementType ();
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];
266 list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
268 list = new ArrayList ();
270 throw new InvalidOperationException (String.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
272 if (list.IsReadOnly) {
277 if (elementType == null)
278 elementType = typeof (object);
280 foreach (object value in col)
281 list.Add (ConvertToType (value, elementType));
283 if (type != null && type.IsArray)
284 list = ((ArrayList) list).ToArray (elementType);
289 object ConvertToObject (IDictionary<string, object> dict, Type type)
291 if (_typeResolver != null) {
292 if (dict.Keys.Contains(SerializedTypeNameKey)) {
294 type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
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]);
309 } else if (type.IsAssignableFrom (typeof (IDictionary)))
310 type = typeof (Dictionary <string, object>);
312 object target = Activator.CreateInstance (type, true);
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 ();
321 ((IDictionary) target).Add (entry.Key, ConvertToType (value, valueType));
324 MemberInfo [] memberCollection = type.GetMember (entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
325 if (memberCollection == null || memberCollection.Length == 0) {
326 //must evaluate value
331 MemberInfo member = memberCollection [0];
333 if (!ReflectionUtils.CanSetMemberValue (member)) {
334 //must evaluate value
339 Type memberType = ReflectionUtils.GetMemberUnderlyingType (member);
341 if (memberType.IsInterface) {
342 if (memberType.IsGenericType)
343 memberType = ResolveGenericInterfaceToType (memberType);
345 memberType = ResolveInterfaceToType (memberType);
347 if (memberType == null)
348 throw new InvalidOperationException ("Unable to deserialize a member, as its type is an unknown interface.");
351 ReflectionUtils.SetMemberValue (member, target, ConvertToType(value, memberType));
357 Type ResolveGenericInterfaceToType (Type type)
359 Type[] genericArgs = type.GetGenericArguments ();
361 if (ReflectionUtils.IsSubClass (type, typeof (IDictionary <,>)))
362 return typeof (Dictionary <,>).MakeGenericType (genericArgs);
364 if (ReflectionUtils.IsSubClass (type, typeof (IList <>)) ||
365 ReflectionUtils.IsSubClass (type, typeof (ICollection <>)) ||
366 ReflectionUtils.IsSubClass (type, typeof (IEnumerable <>))
368 return typeof (List <>).MakeGenericType (genericArgs);
370 if (ReflectionUtils.IsSubClass (type, typeof (IComparer <>)))
371 return typeof (Comparer <>).MakeGenericType (genericArgs);
373 if (ReflectionUtils.IsSubClass (type, typeof (IEqualityComparer <>)))
374 return typeof (EqualityComparer <>).MakeGenericType (genericArgs);
379 Type ResolveInterfaceToType (Type type)
381 if (typeof (IDictionary).IsAssignableFrom (type))
382 return typeof (Hashtable);
384 if (typeof (IList).IsAssignableFrom (type) ||
385 typeof (ICollection).IsAssignableFrom (type) ||
386 typeof (IEnumerable).IsAssignableFrom (type))
387 return typeof (ArrayList);
389 if (typeof (IComparer).IsAssignableFrom (type))
390 return typeof (Comparer);
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");
403 obj = ConvertToType(obj, null);
408 internal object DeserializeObjectInternal (string input) {
409 return Json.Deserialize (input, this);
412 internal object DeserializeObjectInternal (TextReader input) {
413 return Json.Deserialize (input, this);
416 public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
417 if (converters == null)
418 throw new ArgumentNullException ("converters");
420 if (_converterList == null)
421 _converterList = new List<IEnumerable<JavaScriptConverter>> ();
422 _converterList.Add (converters);
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))
437 public string Serialize (object obj) {
438 StringBuilder b = new StringBuilder ();
440 return b.ToString ();
443 public void Serialize (object obj, StringBuilder output) {
444 Json.Serialize (obj, this, output);
447 internal void Serialize (object obj, TextWriter output) {
448 Json.Serialize (obj, this, output);