JavaScriptSerializer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. //
  2. // JavaScriptSerializer.cs
  3. //
  4. // Author:
  5. // Konstantin Triger <[email protected]>
  6. //
  7. // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Text;
  32. using Newtonsoft.Json;
  33. using System.IO;
  34. using System.Collections;
  35. using System.Reflection;
  36. using Newtonsoft.Json.Utilities;
  37. using System.ComponentModel;
  38. using System.Configuration;
  39. using System.Web.Configuration;
  40. namespace System.Web.Script.Serialization
  41. {
  42. public class JavaScriptSerializer
  43. {
  44. internal const string SerializedTypeNameKey = "__type";
  45. List<IEnumerable<JavaScriptConverter>> _converterList;
  46. int _maxJsonLength;
  47. int _recursionLimit;
  48. JavaScriptTypeResolver _typeResolver;
  49. internal static readonly JavaScriptSerializer DefaultSerializer = new JavaScriptSerializer (null, false);
  50. public JavaScriptSerializer () : this (null, false)
  51. {
  52. }
  53. public JavaScriptSerializer (JavaScriptTypeResolver resolver) : this (resolver, false)
  54. {
  55. }
  56. internal JavaScriptSerializer (JavaScriptTypeResolver resolver, bool registerConverters)
  57. {
  58. _typeResolver = resolver;
  59. ScriptingJsonSerializationSection section = (ScriptingJsonSerializationSection) ConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/jsonSerialization");
  60. if (section == null) {
  61. #if NET_3_5
  62. _maxJsonLength = 2097152;
  63. #else
  64. _maxJsonLength = 102400;
  65. #endif
  66. _recursionLimit = 100;
  67. } else {
  68. _maxJsonLength = section.MaxJsonLength;
  69. _recursionLimit = section.RecursionLimit;
  70. if (registerConverters) {
  71. ConvertersCollection converters = section.Converters;
  72. if (converters != null && converters.Count > 0) {
  73. var cvtlist = new List <JavaScriptConverter> ();
  74. Type type;
  75. string typeName;
  76. JavaScriptConverter jsc;
  77. foreach (Converter cvt in converters) {
  78. typeName = cvt != null ? cvt.Type : null;
  79. if (typeName == null)
  80. continue;
  81. type = HttpApplication.LoadType (typeName, true);
  82. if (type == null || !typeof (JavaScriptConverter).IsAssignableFrom (type))
  83. continue;
  84. jsc = Activator.CreateInstance (type) as JavaScriptConverter;
  85. cvtlist.Add (jsc);
  86. }
  87. RegisterConverters (cvtlist);
  88. }
  89. }
  90. }
  91. }
  92. public int MaxJsonLength {
  93. get {
  94. return _maxJsonLength;
  95. }
  96. set {
  97. _maxJsonLength = value;
  98. }
  99. }
  100. public int RecursionLimit {
  101. get {
  102. return _recursionLimit;
  103. }
  104. set {
  105. _recursionLimit = value;
  106. }
  107. }
  108. internal JavaScriptTypeResolver TypeResolver {
  109. get { return _typeResolver; }
  110. }
  111. public T ConvertToType<T> (object obj) {
  112. if (obj == null)
  113. return default (T);
  114. return (T) ConvertToType (typeof (T), obj);
  115. }
  116. internal object ConvertToType (Type type, object obj) {
  117. if (obj == null)
  118. return null;
  119. if (obj is IDictionary<string, object>) {
  120. if (type == null)
  121. obj = EvaluateDictionary ((IDictionary<string, object>) obj);
  122. else {
  123. JavaScriptConverter converter = GetConverter (type);
  124. if (converter != null)
  125. return converter.Deserialize (
  126. EvaluateDictionary ((IDictionary<string, object>) obj),
  127. type, this);
  128. }
  129. return ConvertToObject ((IDictionary<string, object>) obj, type);
  130. }
  131. if (obj is ArrayList)
  132. return ConvertToList ((ArrayList) obj, type);
  133. if (type == null)
  134. return obj;
  135. Type sourceType = obj.GetType ();
  136. if (type.IsAssignableFrom (sourceType))
  137. return obj;
  138. if (type.IsEnum)
  139. if (obj is string)
  140. return Enum.Parse (type, (string) obj, true);
  141. else
  142. return Enum.ToObject (type, obj);
  143. TypeConverter c = TypeDescriptor.GetConverter (type);
  144. if (c.CanConvertFrom (sourceType)) {
  145. if (obj is string)
  146. return c.ConvertFromInvariantString ((string) obj);
  147. return c.ConvertFrom (obj);
  148. }
  149. /*
  150. * Take care of the special case whereas in JSON an empty string ("") really means
  151. * an empty value
  152. * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
  153. */
  154. if ( (type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Nullable<>)) )
  155. {
  156. string s = obj as String;
  157. if (String.IsNullOrEmpty(s))
  158. return null;
  159. }
  160. return Convert.ChangeType (obj, type);
  161. }
  162. public T Deserialize<T> (string input) {
  163. return ConvertToType<T> (DeserializeObjectInternal(input));
  164. }
  165. static object Evaluate (object value) {
  166. return Evaluate (value, false);
  167. }
  168. static object Evaluate (object value, bool convertListToArray) {
  169. if (value is IDictionary<string, object>)
  170. value = EvaluateDictionary ((IDictionary<string, object>) value, convertListToArray);
  171. else if (value is ArrayList)
  172. value = EvaluateList ((ArrayList) value, convertListToArray);
  173. return value;
  174. }
  175. static object EvaluateList (ArrayList e) {
  176. return EvaluateList (e, false);
  177. }
  178. static object EvaluateList (ArrayList e, bool convertListToArray) {
  179. ArrayList list = new ArrayList ();
  180. foreach (object value in e)
  181. list.Add (Evaluate (value, convertListToArray));
  182. return convertListToArray ? (object) list.ToArray () : list;
  183. }
  184. static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
  185. return EvaluateDictionary (dict, false);
  186. }
  187. static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict, bool convertListToArray) {
  188. Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
  189. foreach (KeyValuePair<string, object> entry in dict) {
  190. d.Add (entry.Key, Evaluate (entry.Value, convertListToArray));
  191. }
  192. return d;
  193. }
  194. static readonly Type typeofObject = typeof(object);
  195. static readonly Type typeofGenList = typeof (List<>);
  196. object ConvertToList (ArrayList col, Type type) {
  197. Type elementType = null;
  198. if (type != null && type.HasElementType)
  199. elementType = type.GetElementType ();
  200. IList list;
  201. if (type == null || type.IsArray || typeofObject == type || typeof (ArrayList).IsAssignableFrom (type))
  202. list = new ArrayList ();
  203. else if (ReflectionUtils.IsInstantiatableType (type))
  204. // non-generic typed list
  205. list = (IList) Activator.CreateInstance (type, true);
  206. else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
  207. if (type.IsGenericType) {
  208. Type [] genArgs = type.GetGenericArguments ();
  209. elementType = genArgs [0];
  210. // generic list
  211. list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
  212. } else
  213. list = new ArrayList ();
  214. } else
  215. throw new InvalidOperationException (String.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
  216. if (list.IsReadOnly) {
  217. EvaluateList (col);
  218. return list;
  219. }
  220. foreach (object value in col)
  221. list.Add (ConvertToType (elementType, value));
  222. if (type != null && type.IsArray)
  223. list = ((ArrayList) list).ToArray (elementType);
  224. return list;
  225. }
  226. object ConvertToObject (IDictionary<string, object> dict, Type type)
  227. {
  228. if (_typeResolver != null) {
  229. if (dict.Keys.Contains(SerializedTypeNameKey)) {
  230. // already Evaluated
  231. type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
  232. }
  233. }
  234. if (type.IsGenericType) {
  235. if (type.GetGenericTypeDefinition ().IsAssignableFrom (typeof (IDictionary <,>))) {
  236. Type[] arguments = type.GetGenericArguments ();
  237. if (arguments == null || arguments.Length != 2 || (arguments [0] != typeof (object) && arguments [0] != typeof (string)))
  238. throw new InvalidOperationException (
  239. "Type '" + type + "' is not not supported for serialization/deserialization of a dictionary, keys must be strings or objects.");
  240. if (type.IsAbstract) {
  241. Type dictType = typeof (Dictionary <,>);
  242. type = dictType.MakeGenericType (arguments [0], arguments [1]);
  243. }
  244. }
  245. } else if (type.IsAssignableFrom (typeof (IDictionary)))
  246. type = typeof (Dictionary <string, object>);
  247. object target = Activator.CreateInstance (type, true);
  248. foreach (KeyValuePair<string, object> entry in dict) {
  249. object value = entry.Value;
  250. if (target is IDictionary) {
  251. Type valueType = ReflectionUtils.GetTypedDictionaryValueType (type);
  252. if (value != null && valueType == typeof (System.Object))
  253. valueType = value.GetType ();
  254. ((IDictionary) target).Add (entry.Key, ConvertToType (valueType, value));
  255. continue;
  256. }
  257. MemberInfo [] memberCollection = type.GetMember (entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
  258. if (memberCollection == null || memberCollection.Length == 0) {
  259. //must evaluate value
  260. Evaluate (value);
  261. continue;
  262. }
  263. MemberInfo member = memberCollection [0];
  264. if (!ReflectionUtils.CanSetMemberValue (member)) {
  265. //must evaluate value
  266. Evaluate (value);
  267. continue;
  268. }
  269. Type memberType = ReflectionUtils.GetMemberUnderlyingType (member);
  270. if (memberType.IsInterface) {
  271. if (memberType.IsGenericType)
  272. memberType = ResolveGenericInterfaceToType (memberType);
  273. else
  274. memberType = ResolveInterfaceToType (memberType);
  275. if (memberType == null)
  276. throw new InvalidOperationException ("Unable to deserialize a member, as its type is an unknown interface.");
  277. }
  278. ReflectionUtils.SetMemberValue (member, target, ConvertToType(memberType, value));
  279. }
  280. return target;
  281. }
  282. Type ResolveGenericInterfaceToType (Type type)
  283. {
  284. Type[] genericArgs = type.GetGenericArguments ();
  285. if (ReflectionUtils.IsSubClass (type, typeof (IDictionary <,>)))
  286. return typeof (Dictionary <,>).MakeGenericType (genericArgs);
  287. if (ReflectionUtils.IsSubClass (type, typeof (IList <>)) ||
  288. ReflectionUtils.IsSubClass (type, typeof (ICollection <>)) ||
  289. ReflectionUtils.IsSubClass (type, typeof (IEnumerable <>))
  290. )
  291. return typeof (List <>).MakeGenericType (genericArgs);
  292. if (ReflectionUtils.IsSubClass (type, typeof (IComparer <>)))
  293. return typeof (Comparer <>).MakeGenericType (genericArgs);
  294. if (ReflectionUtils.IsSubClass (type, typeof (IEqualityComparer <>)))
  295. return typeof (EqualityComparer <>).MakeGenericType (genericArgs);
  296. return null;
  297. }
  298. Type ResolveInterfaceToType (Type type)
  299. {
  300. if (typeof (IDictionary).IsAssignableFrom (type))
  301. return typeof (Hashtable);
  302. if (typeof (IList).IsAssignableFrom (type) ||
  303. typeof (ICollection).IsAssignableFrom (type) ||
  304. typeof (IEnumerable).IsAssignableFrom (type))
  305. return typeof (ArrayList);
  306. if (typeof (IComparer).IsAssignableFrom (type))
  307. return typeof (Comparer);
  308. return null;
  309. }
  310. public object DeserializeObject (string input) {
  311. object obj = Evaluate (DeserializeObjectInternal (input), true);
  312. IDictionary dictObj = obj as IDictionary;
  313. if (dictObj != null && dictObj.Contains(SerializedTypeNameKey)){
  314. if (_typeResolver == null) {
  315. throw new ArgumentNullException ("resolver", "Must have a type resolver to deserialize an object that has an '__type' member");
  316. }
  317. obj = ConvertToType(null, obj);
  318. }
  319. return obj;
  320. }
  321. internal object DeserializeObjectInternal (string input) {
  322. return Json.Deserialize (input, this);
  323. }
  324. internal object DeserializeObjectInternal (TextReader input) {
  325. return Json.Deserialize (input, this);
  326. }
  327. public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
  328. if (converters == null)
  329. throw new ArgumentNullException ("converters");
  330. if (_converterList == null)
  331. _converterList = new List<IEnumerable<JavaScriptConverter>> ();
  332. _converterList.Add (converters);
  333. }
  334. internal JavaScriptConverter GetConverter (Type type) {
  335. if (_converterList != null)
  336. for (int i = 0; i < _converterList.Count; i++) {
  337. foreach (JavaScriptConverter converter in _converterList [i])
  338. foreach (Type supportedType in converter.SupportedTypes)
  339. if (supportedType.IsAssignableFrom (type))
  340. return converter;
  341. }
  342. return null;
  343. }
  344. public string Serialize (object obj) {
  345. StringBuilder b = new StringBuilder ();
  346. Serialize (obj, b);
  347. return b.ToString ();
  348. }
  349. public void Serialize (object obj, StringBuilder output) {
  350. Json.Serialize (obj, this, output);
  351. }
  352. internal void Serialize (object obj, TextWriter output) {
  353. Json.Serialize (obj, this, output);
  354. }
  355. }
  356. }