JavaScriptSerializer.cs 14 KB

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