JavaScriptSerializer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. //
  2. // JavaScriptSerializer.cs
  3. //
  4. // Authors:
  5. // Konstantin Triger <[email protected]>
  6. // Marek Safar <[email protected]>
  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. if ((targetType.IsGenericType) && (targetType.GetGenericTypeDefinition () == typeof (Nullable<>))) {
  157. if (obj is String) {
  158. /*
  159. * Take care of the special case whereas in JSON an empty string ("") really means
  160. * an empty value
  161. * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
  162. */
  163. if(String.IsNullOrEmpty ((String)obj))
  164. return null;
  165. } else if (c.CanConvertFrom (typeof (string))) {
  166. TypeConverter objConverter = TypeDescriptor.GetConverter (obj);
  167. string s = objConverter.ConvertToInvariantString (obj);
  168. return c.ConvertFromInvariantString (s);
  169. }
  170. }
  171. return Convert.ChangeType (obj, targetType);
  172. }
  173. public T Deserialize<T> (string input) {
  174. return ConvertToType<T> (DeserializeObjectInternal(input));
  175. }
  176. public object Deserialize (string input, Type targetType) {
  177. return DeserializeObjectInternal (input);
  178. }
  179. static object Evaluate (object value) {
  180. return Evaluate (value, false);
  181. }
  182. static object Evaluate (object value, bool convertListToArray) {
  183. if (value is IDictionary<string, object>)
  184. value = EvaluateDictionary ((IDictionary<string, object>) value, convertListToArray);
  185. else if (value is ArrayList)
  186. value = EvaluateList ((ArrayList) value, convertListToArray);
  187. return value;
  188. }
  189. static object EvaluateList (ArrayList e) {
  190. return EvaluateList (e, false);
  191. }
  192. static object EvaluateList (ArrayList e, bool convertListToArray) {
  193. ArrayList list = new ArrayList ();
  194. foreach (object value in e)
  195. list.Add (Evaluate (value, convertListToArray));
  196. return convertListToArray ? (object) list.ToArray () : list;
  197. }
  198. static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
  199. return EvaluateDictionary (dict, false);
  200. }
  201. static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict, bool convertListToArray) {
  202. Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
  203. foreach (KeyValuePair<string, object> entry in dict) {
  204. d.Add (entry.Key, Evaluate (entry.Value, convertListToArray));
  205. }
  206. return d;
  207. }
  208. static readonly Type typeofObject = typeof(object);
  209. static readonly Type typeofGenList = typeof (List<>);
  210. object ConvertToList (ArrayList col, Type type) {
  211. Type elementType = null;
  212. if (type != null && type.HasElementType)
  213. elementType = type.GetElementType ();
  214. IList list;
  215. if (type == null || type.IsArray || typeofObject == type || typeof (ArrayList).IsAssignableFrom (type))
  216. list = new ArrayList ();
  217. else if (ReflectionUtils.IsInstantiatableType (type))
  218. // non-generic typed list
  219. list = (IList) Activator.CreateInstance (type, true);
  220. else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
  221. if (type.IsGenericType) {
  222. Type [] genArgs = type.GetGenericArguments ();
  223. elementType = genArgs [0];
  224. // generic list
  225. list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
  226. } else
  227. list = new ArrayList ();
  228. } else
  229. throw new InvalidOperationException (String.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
  230. if (list.IsReadOnly) {
  231. EvaluateList (col);
  232. return list;
  233. }
  234. if (elementType == null)
  235. elementType = typeof (object);
  236. foreach (object value in col)
  237. list.Add (ConvertToType (value, elementType));
  238. if (type != null && type.IsArray)
  239. list = ((ArrayList) list).ToArray (elementType);
  240. return list;
  241. }
  242. object ConvertToObject (IDictionary<string, object> dict, Type type)
  243. {
  244. if (_typeResolver != null) {
  245. if (dict.Keys.Contains(SerializedTypeNameKey)) {
  246. // already Evaluated
  247. type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
  248. }
  249. }
  250. if (type.IsGenericType) {
  251. if (type.GetGenericTypeDefinition ().IsAssignableFrom (typeof (IDictionary <,>))) {
  252. Type[] arguments = type.GetGenericArguments ();
  253. if (arguments == null || arguments.Length != 2 || (arguments [0] != typeof (object) && arguments [0] != typeof (string)))
  254. throw new InvalidOperationException (
  255. "Type '" + type + "' is not not supported for serialization/deserialization of a dictionary, keys must be strings or objects.");
  256. if (type.IsAbstract) {
  257. Type dictType = typeof (Dictionary <,>);
  258. type = dictType.MakeGenericType (arguments [0], arguments [1]);
  259. }
  260. }
  261. } else if (type.IsAssignableFrom (typeof (IDictionary)))
  262. type = typeof (Dictionary <string, object>);
  263. object target = Activator.CreateInstance (type, true);
  264. foreach (KeyValuePair<string, object> entry in dict) {
  265. object value = entry.Value;
  266. if (target is IDictionary) {
  267. Type valueType = ReflectionUtils.GetTypedDictionaryValueType (type);
  268. if (value != null && valueType == typeof (System.Object))
  269. valueType = value.GetType ();
  270. ((IDictionary) target).Add (entry.Key, ConvertToType (value, valueType));
  271. continue;
  272. }
  273. MemberInfo [] memberCollection = type.GetMember (entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
  274. if (memberCollection == null || memberCollection.Length == 0) {
  275. //must evaluate value
  276. Evaluate (value);
  277. continue;
  278. }
  279. MemberInfo member = memberCollection [0];
  280. if (!ReflectionUtils.CanSetMemberValue (member)) {
  281. //must evaluate value
  282. Evaluate (value);
  283. continue;
  284. }
  285. Type memberType = ReflectionUtils.GetMemberUnderlyingType (member);
  286. if (memberType.IsInterface) {
  287. if (memberType.IsGenericType)
  288. memberType = ResolveGenericInterfaceToType (memberType);
  289. else
  290. memberType = ResolveInterfaceToType (memberType);
  291. if (memberType == null)
  292. throw new InvalidOperationException ("Unable to deserialize a member, as its type is an unknown interface.");
  293. }
  294. ReflectionUtils.SetMemberValue (member, target, ConvertToType(value, memberType));
  295. }
  296. return target;
  297. }
  298. Type ResolveGenericInterfaceToType (Type type)
  299. {
  300. Type[] genericArgs = type.GetGenericArguments ();
  301. if (ReflectionUtils.IsSubClass (type, typeof (IDictionary <,>)))
  302. return typeof (Dictionary <,>).MakeGenericType (genericArgs);
  303. if (ReflectionUtils.IsSubClass (type, typeof (IList <>)) ||
  304. ReflectionUtils.IsSubClass (type, typeof (ICollection <>)) ||
  305. ReflectionUtils.IsSubClass (type, typeof (IEnumerable <>))
  306. )
  307. return typeof (List <>).MakeGenericType (genericArgs);
  308. if (ReflectionUtils.IsSubClass (type, typeof (IComparer <>)))
  309. return typeof (Comparer <>).MakeGenericType (genericArgs);
  310. if (ReflectionUtils.IsSubClass (type, typeof (IEqualityComparer <>)))
  311. return typeof (EqualityComparer <>).MakeGenericType (genericArgs);
  312. return null;
  313. }
  314. Type ResolveInterfaceToType (Type type)
  315. {
  316. if (typeof (IDictionary).IsAssignableFrom (type))
  317. return typeof (Hashtable);
  318. if (typeof (IList).IsAssignableFrom (type) ||
  319. typeof (ICollection).IsAssignableFrom (type) ||
  320. typeof (IEnumerable).IsAssignableFrom (type))
  321. return typeof (ArrayList);
  322. if (typeof (IComparer).IsAssignableFrom (type))
  323. return typeof (Comparer);
  324. return null;
  325. }
  326. public object DeserializeObject (string input) {
  327. object obj = Evaluate (DeserializeObjectInternal (input), true);
  328. IDictionary dictObj = obj as IDictionary;
  329. if (dictObj != null && dictObj.Contains(SerializedTypeNameKey)){
  330. if (_typeResolver == null) {
  331. throw new ArgumentNullException ("resolver", "Must have a type resolver to deserialize an object that has an '__type' member");
  332. }
  333. obj = ConvertToType(obj, null);
  334. }
  335. return obj;
  336. }
  337. internal object DeserializeObjectInternal (string input) {
  338. return Json.Deserialize (input, this);
  339. }
  340. internal object DeserializeObjectInternal (TextReader input) {
  341. return Json.Deserialize (input, this);
  342. }
  343. public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
  344. if (converters == null)
  345. throw new ArgumentNullException ("converters");
  346. if (_converterList == null)
  347. _converterList = new List<IEnumerable<JavaScriptConverter>> ();
  348. _converterList.Add (converters);
  349. }
  350. internal JavaScriptConverter GetConverter (Type type) {
  351. if (_converterList != null)
  352. for (int i = 0; i < _converterList.Count; i++) {
  353. foreach (JavaScriptConverter converter in _converterList [i])
  354. foreach (Type supportedType in converter.SupportedTypes)
  355. if (supportedType.IsAssignableFrom (type))
  356. return converter;
  357. }
  358. return null;
  359. }
  360. public string Serialize (object obj) {
  361. StringBuilder b = new StringBuilder ();
  362. Serialize (obj, b);
  363. return b.ToString ();
  364. }
  365. public void Serialize (object obj, StringBuilder output) {
  366. Json.Serialize (obj, this, output);
  367. }
  368. internal void Serialize (object obj, TextWriter output) {
  369. Json.Serialize (obj, this, output);
  370. }
  371. }
  372. }