JavaScriptSerializer.cs 11 KB

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