JavaScriptSerializer.cs 11 KB

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