PageRenderTime 49ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/mcs/class/System.Web.Extensions/System.Web.Script.Serialization/JavaScriptSerializer.cs

https://bitbucket.org/danipen/mono
C# | 443 lines | 326 code | 78 blank | 39 comment | 108 complexity | ef2d3ea8918e89173c5fe785ebce7ef4 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  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. using System;
  31. using System.Collections.Generic;
  32. using System.Text;
  33. using Newtonsoft.Json;
  34. using System.IO;
  35. using System.Collections;
  36. using System.Reflection;
  37. using Newtonsoft.Json.Utilities;
  38. using System.ComponentModel;
  39. using System.Configuration;
  40. using System.Web.Configuration;
  41. namespace System.Web.Script.Serialization
  42. {
  43. public class JavaScriptSerializer
  44. {
  45. internal const string SerializedTypeNameKey = "__type";
  46. List<IEnumerable<JavaScriptConverter>> _converterList;
  47. int _maxJsonLength;
  48. int _recursionLimit;
  49. JavaScriptTypeResolver _typeResolver;
  50. internal static readonly JavaScriptSerializer DefaultSerializer = new JavaScriptSerializer (null, false);
  51. public JavaScriptSerializer () : this (null, false)
  52. {
  53. }
  54. public JavaScriptSerializer (JavaScriptTypeResolver resolver) : this (resolver, false)
  55. {
  56. }
  57. internal JavaScriptSerializer (JavaScriptTypeResolver resolver, bool registerConverters)
  58. {
  59. _typeResolver = resolver;
  60. ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection) ConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/jsonSerialization");
  61. if (section == null) {
  62. #if NET_3_5
  63. _maxJsonLength = 2097152;
  64. #else
  65. _maxJsonLength = 102400;
  66. #endif
  67. _recursionLimit = 100;
  68. } else {
  69. _maxJsonLength = section.MaxJsonLength;
  70. _recursionLimit = section.RecursionLimit;
  71. if (registerConverters) {
  72. ConvertersCollection converters = section.Converters;
  73. if (converters != null && converters.Count > 0) {
  74. var cvtlist = new List <JavaScriptConverter> ();
  75. Type type;
  76. string typeName;
  77. JavaScriptConverter jsc;
  78. foreach (Converter cvt in converters) {
  79. typeName = cvt != null ? cvt.Type : null;
  80. if (typeName == null)
  81. continue;
  82. type = HttpApplication.LoadType (typeName, true);
  83. if (type == null || !typeof (JavaScriptConverter).IsAssignableFrom (type))
  84. continue;
  85. jsc = Activator.CreateInstance (type) as JavaScriptConverter;
  86. cvtlist.Add (jsc);
  87. }
  88. RegisterConverters (cvtlist);
  89. }
  90. }
  91. }
  92. }
  93. public int MaxJsonLength {
  94. get {
  95. return _maxJsonLength;
  96. }
  97. set {
  98. _maxJsonLength = value;
  99. }
  100. }
  101. public int RecursionLimit {
  102. get {
  103. return _recursionLimit;
  104. }
  105. set {
  106. _recursionLimit = value;
  107. }
  108. }
  109. internal JavaScriptTypeResolver TypeResolver {
  110. get { return _typeResolver; }
  111. }
  112. public T ConvertToType<T> (object obj) {
  113. if (obj == null)
  114. return default (T);
  115. return (T) ConvertToType (obj, typeof (T));
  116. }
  117. #if NET_4_0
  118. public
  119. #else
  120. internal
  121. #endif
  122. object ConvertToType (object obj, Type targetType)
  123. {
  124. if (obj == null)
  125. return null;
  126. if (obj is IDictionary<string, object>) {
  127. if (targetType == null)
  128. obj = EvaluateDictionary ((IDictionary<string, object>) obj);
  129. else {
  130. JavaScriptConverter converter = GetConverter (targetType);
  131. if (converter != null)
  132. return converter.Deserialize (
  133. EvaluateDictionary ((IDictionary<string, object>) obj),
  134. targetType, this);
  135. }
  136. return ConvertToObject ((IDictionary<string, object>) obj, targetType);
  137. }
  138. if (obj is ArrayList)
  139. return ConvertToList ((ArrayList) obj, targetType);
  140. if (targetType == null)
  141. return obj;
  142. Type sourceType = obj.GetType ();
  143. if (targetType.IsAssignableFrom (sourceType))
  144. return obj;
  145. if (targetType.IsEnum)
  146. if (obj is string)
  147. return Enum.Parse (targetType, (string) obj, true);
  148. else
  149. return Enum.ToObject (targetType, obj);
  150. TypeConverter c = TypeDescriptor.GetConverter (targetType);
  151. if (c.CanConvertFrom (sourceType)) {
  152. if (obj is string)
  153. return c.ConvertFromInvariantString ((string) obj);
  154. return c.ConvertFrom (obj);
  155. }
  156. /*
  157. * Take care of the special case whereas in JSON an empty string ("") really means
  158. * an empty value
  159. * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
  160. */
  161. if ((targetType.IsGenericType) && (targetType.GetGenericTypeDefinition() == typeof(Nullable<>)))
  162. {
  163. string s = obj as String;
  164. if (String.IsNullOrEmpty(s))
  165. return null;
  166. }
  167. return Convert.ChangeType (obj, targetType);
  168. }
  169. public T Deserialize<T> (string input) {
  170. return ConvertToType<T> (DeserializeObjectInternal(input));
  171. }
  172. static object Evaluate (object value) {
  173. return Evaluate (value, false);
  174. }
  175. static object Evaluate (object value, bool convertListToArray) {
  176. if (value is IDictionary<string, object>)
  177. value = EvaluateDictionary ((IDictionary<string, object>) value, convertListToArray);
  178. else if (value is ArrayList)
  179. value = EvaluateList ((ArrayList) value, convertListToArray);
  180. return value;
  181. }
  182. static object EvaluateList (ArrayList e) {
  183. return EvaluateList (e, false);
  184. }
  185. static object EvaluateList (ArrayList e, bool convertListToArray) {
  186. ArrayList list = new ArrayList ();
  187. foreach (object value in e)
  188. list.Add (Evaluate (value, convertListToArray));
  189. return convertListToArray ? (object) list.ToArray () : list;
  190. }
  191. static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
  192. return EvaluateDictionary (dict, false);
  193. }
  194. static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict, bool convertListToArray) {
  195. Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
  196. foreach (KeyValuePair<string, object> entry in dict) {
  197. d.Add (entry.Key, Evaluate (entry.Value, convertListToArray));
  198. }
  199. return d;
  200. }
  201. static readonly Type typeofObject = typeof(object);
  202. static readonly Type typeofGenList = typeof (List<>);
  203. object ConvertToList (ArrayList col, Type type) {
  204. Type elementType = null;
  205. if (type != null && type.HasElementType)
  206. elementType = type.GetElementType ();
  207. IList list;
  208. if (type == null || type.IsArray || typeofObject == type || typeof (ArrayList).IsAssignableFrom (type))
  209. list = new ArrayList ();
  210. else if (ReflectionUtils.IsInstantiatableType (type))
  211. // non-generic typed list
  212. list = (IList) Activator.CreateInstance (type, true);
  213. else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
  214. if (type.IsGenericType) {
  215. Type [] genArgs = type.GetGenericArguments ();
  216. elementType = genArgs [0];
  217. // generic list
  218. list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
  219. } else
  220. list = new ArrayList ();
  221. } else
  222. throw new InvalidOperationException (String.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
  223. if (list.IsReadOnly) {
  224. EvaluateList (col);
  225. return list;
  226. }
  227. if (elementType == null)
  228. elementType = typeof (object);
  229. foreach (object value in col)
  230. list.Add (ConvertToType (value, elementType));
  231. if (type != null && type.IsArray)
  232. list = ((ArrayList) list).ToArray (elementType);
  233. return list;
  234. }
  235. object ConvertToObject (IDictionary<string, object> dict, Type type)
  236. {
  237. if (_typeResolver != null) {
  238. if (dict.Keys.Contains(SerializedTypeNameKey)) {
  239. // already Evaluated
  240. type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
  241. }
  242. }
  243. if (type.IsGenericType) {
  244. if (type.GetGenericTypeDefinition ().IsAssignableFrom (typeof (IDictionary <,>))) {
  245. Type[] arguments = type.GetGenericArguments ();
  246. if (arguments == null || arguments.Length != 2 || (arguments [0] != typeof (object) && arguments [0] != typeof (string)))
  247. throw new InvalidOperationException (
  248. "Type '" + type + "' is not not supported for serialization/deserialization of a dictionary, keys must be strings or objects.");
  249. if (type.IsAbstract) {
  250. Type dictType = typeof (Dictionary <,>);
  251. type = dictType.MakeGenericType (arguments [0], arguments [1]);
  252. }
  253. }
  254. } else if (type.IsAssignableFrom (typeof (IDictionary)))
  255. type = typeof (Dictionary <string, object>);
  256. object target = Activator.CreateInstance (type, true);
  257. foreach (KeyValuePair<string, object> entry in dict) {
  258. object value = entry.Value;
  259. if (target is IDictionary) {
  260. Type valueType = ReflectionUtils.GetTypedDictionaryValueType (type);
  261. if (value != null && valueType == typeof (System.Object))
  262. valueType = value.GetType ();
  263. ((IDictionary) target).Add (entry.Key, ConvertToType (value, valueType));
  264. continue;
  265. }
  266. MemberInfo [] memberCollection = type.GetMember (entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
  267. if (memberCollection == null || memberCollection.Length == 0) {
  268. //must evaluate value
  269. Evaluate (value);
  270. continue;
  271. }
  272. MemberInfo member = memberCollection [0];
  273. if (!ReflectionUtils.CanSetMemberValue (member)) {
  274. //must evaluate value
  275. Evaluate (value);
  276. continue;
  277. }
  278. Type memberType = ReflectionUtils.GetMemberUnderlyingType (member);
  279. if (memberType.IsInterface) {
  280. if (memberType.IsGenericType)
  281. memberType = ResolveGenericInterfaceToType (memberType);
  282. else
  283. memberType = ResolveInterfaceToType (memberType);
  284. if (memberType == null)
  285. throw new InvalidOperationException ("Unable to deserialize a member, as its type is an unknown interface.");
  286. }
  287. ReflectionUtils.SetMemberValue (member, target, ConvertToType(value, memberType));
  288. }
  289. return target;
  290. }
  291. Type ResolveGenericInterfaceToType (Type type)
  292. {
  293. Type[] genericArgs = type.GetGenericArguments ();
  294. if (ReflectionUtils.IsSubClass (type, typeof (IDictionary <,>)))
  295. return typeof (Dictionary <,>).MakeGenericType (genericArgs);
  296. if (ReflectionUtils.IsSubClass (type, typeof (IList <>)) ||
  297. ReflectionUtils.IsSubClass (type, typeof (ICollection <>)) ||
  298. ReflectionUtils.IsSubClass (type, typeof (IEnumerable <>))
  299. )
  300. return typeof (List <>).MakeGenericType (genericArgs);
  301. if (ReflectionUtils.IsSubClass (type, typeof (IComparer <>)))
  302. return typeof (Comparer <>).MakeGenericType (genericArgs);
  303. if (ReflectionUtils.IsSubClass (type, typeof (IEqualityComparer <>)))
  304. return typeof (EqualityComparer <>).MakeGenericType (genericArgs);
  305. return null;
  306. }
  307. Type ResolveInterfaceToType (Type type)
  308. {
  309. if (typeof (IDictionary).IsAssignableFrom (type))
  310. return typeof (Hashtable);
  311. if (typeof (IList).IsAssignableFrom (type) ||
  312. typeof (ICollection).IsAssignableFrom (type) ||
  313. typeof (IEnumerable).IsAssignableFrom (type))
  314. return typeof (ArrayList);
  315. if (typeof (IComparer).IsAssignableFrom (type))
  316. return typeof (Comparer);
  317. return null;
  318. }
  319. public object DeserializeObject (string input) {
  320. object obj = Evaluate (DeserializeObjectInternal (input), true);
  321. IDictionary dictObj = obj as IDictionary;
  322. if (dictObj != null && dictObj.Contains(SerializedTypeNameKey)){
  323. if (_typeResolver == null) {
  324. throw new ArgumentNullException ("resolver", "Must have a type resolver to deserialize an object that has an '__type' member");
  325. }
  326. obj = ConvertToType(obj, null);
  327. }
  328. return obj;
  329. }
  330. internal object DeserializeObjectInternal (string input) {
  331. return Json.Deserialize (input, this);
  332. }
  333. internal object DeserializeObjectInternal (TextReader input) {
  334. return Json.Deserialize (input, this);
  335. }
  336. public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
  337. if (converters == null)
  338. throw new ArgumentNullException ("converters");
  339. if (_converterList == null)
  340. _converterList = new List<IEnumerable<JavaScriptConverter>> ();
  341. _converterList.Add (converters);
  342. }
  343. internal JavaScriptConverter GetConverter (Type type) {
  344. if (_converterList != null)
  345. for (int i = 0; i < _converterList.Count; i++) {
  346. foreach (JavaScriptConverter converter in _converterList [i])
  347. foreach (Type supportedType in converter.SupportedTypes)
  348. if (supportedType.IsAssignableFrom (type))
  349. return converter;
  350. }
  351. return null;
  352. }
  353. public string Serialize (object obj) {
  354. StringBuilder b = new StringBuilder ();
  355. Serialize (obj, b);
  356. return b.ToString ();
  357. }
  358. public void Serialize (object obj, StringBuilder output) {
  359. Json.Serialize (obj, this, output);
  360. }
  361. internal void Serialize (object obj, TextWriter output) {
  362. Json.Serialize (obj, this, output);
  363. }
  364. }
  365. }