JavaScriptSerializer.cs 13 KB

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