JavaScriptSerializer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. //TODO: use it!
  131. public int MaxJsonLength {
  132. get {
  133. return _maxJsonLength;
  134. }
  135. set {
  136. _maxJsonLength = value;
  137. }
  138. }
  139. public int RecursionLimit {
  140. get {
  141. return _recursionLimit;
  142. }
  143. set {
  144. _recursionLimit = value;
  145. }
  146. }
  147. public T ConvertToType<T> (object obj) {
  148. if (obj == null)
  149. return default (T);
  150. return (T) ConvertToType (typeof (T), obj);
  151. }
  152. internal object ConvertToType (Type type, object obj) {
  153. if (obj == null)
  154. return null;
  155. if (obj is IDictionary<string, object>) {
  156. if (type == null)
  157. obj = Evaluate ((IDictionary<string, object>) obj);
  158. else {
  159. JavaScriptConverter converter = GetConverter (type);
  160. if (converter != null)
  161. return converter.Deserialize (
  162. Evaluate ((IDictionary<string, object>) obj),
  163. type, this);
  164. }
  165. return Deserialize ((IDictionary<string, object>) obj, type);
  166. }
  167. if (obj is IEnumerable<object>)
  168. return Deserialize ((IEnumerable<object>) obj, type);
  169. if (type == null)
  170. return obj;
  171. Type sourceType = obj.GetType ();
  172. if (type.IsAssignableFrom (sourceType))
  173. return obj;
  174. TypeConverter c = TypeDescriptor.GetConverter (type);
  175. if (c.CanConvertFrom(sourceType)) {
  176. if (obj is string)
  177. return c.ConvertFromInvariantString((string)obj);
  178. return c.ConvertFrom (obj);
  179. }
  180. return Convert.ChangeType (obj, type);
  181. }
  182. public T Deserialize<T> (string input) {
  183. return ConvertToType<T> (DeserializeObjectInternal(input));
  184. }
  185. static object Evaluate (object value) {
  186. if (value is IDictionary<string, object>)
  187. value = Evaluate ((IDictionary<string, object>) value);
  188. else
  189. if (value is IEnumerable<object>)
  190. value = Evaluate ((IEnumerable<object>) value);
  191. return value;
  192. }
  193. static object Evaluate (IEnumerable<object> e) {
  194. ArrayList list = new ArrayList ();
  195. foreach (object value in e)
  196. list.Add (Evaluate(value));
  197. return list.ToArray ();
  198. }
  199. static IDictionary<string, object> Evaluate (IDictionary<string, object> dict) {
  200. if (dict is Dictionary<string, object>)
  201. return dict;
  202. Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
  203. foreach (KeyValuePair<string, object> entry in dict)
  204. d.Add (entry.Key, Evaluate(entry.Value));
  205. return d;
  206. }
  207. static readonly Type typeofObject = typeof(object);
  208. static readonly Type typeofGenList = typeof (List<>);
  209. object Deserialize (IEnumerable<object> col, Type type) {
  210. Type elementType = null;
  211. if (type != null && type.HasElementType)
  212. elementType = type.GetElementType ();
  213. IList list;
  214. if (type == null || type.IsArray || typeofObject == type)
  215. list = new ArrayList ();
  216. else if (ReflectionUtils.IsInstantiatableType (type))
  217. // non-generic typed list
  218. list = (IList) Activator.CreateInstance (type, true);
  219. else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
  220. if (type.IsGenericType) {
  221. Type [] genArgs = type.GetGenericArguments ();
  222. elementType = genArgs [0];
  223. // generic list
  224. list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
  225. }
  226. else
  227. list = new ArrayList ();
  228. }
  229. else
  230. throw new JsonSerializationException (string.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
  231. if (list.IsReadOnly) {
  232. Evaluate (col);
  233. return list;
  234. }
  235. foreach (object value in col)
  236. list.Add (ConvertToType (elementType, value));
  237. if (type != null && type.IsArray)
  238. list = ((ArrayList) list).ToArray (elementType);
  239. return list;
  240. }
  241. object Deserialize (IDictionary<string, object> dict, Type type) {
  242. if (type == null)
  243. type = Type.GetType ((string) dict ["__type"]);
  244. object target = Activator.CreateInstance (type, true);
  245. foreach (KeyValuePair<string, object> entry in dict) {
  246. object value = entry.Value;
  247. if (target is IDictionary) {
  248. ((IDictionary) target).Add (entry.Key, ConvertToType (ReflectionUtils.GetTypedDictionaryValueType (type), value));
  249. continue;
  250. }
  251. MemberInfo [] memberCollection = type.GetMember (entry.Key);
  252. if (memberCollection == null || memberCollection.Length == 0) {
  253. //must evaluate value
  254. Evaluate (value);
  255. continue;
  256. }
  257. MemberInfo member = memberCollection [0];
  258. if (!ReflectionUtils.CanSetMemberValue (member)) {
  259. //must evaluate value
  260. Evaluate (value);
  261. continue;
  262. }
  263. ReflectionUtils.SetMemberValue (member, target, ConvertToType(ReflectionUtils.GetMemberUnderlyingType (member), value));
  264. }
  265. return target;
  266. }
  267. public object DeserializeObject (string input) {
  268. return Evaluate (DeserializeObjectInternal (new StringReader (input)));
  269. }
  270. internal object DeserializeObjectInternal (string input) {
  271. return DeserializeObjectInternal (new StringReader (input));
  272. }
  273. internal object DeserializeObjectInternal (TextReader input) {
  274. JsonSerializer ser = new JsonSerializer (this);
  275. return ser.Deserialize (input);
  276. }
  277. public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
  278. if (converters == null)
  279. throw new ArgumentNullException ("converters");
  280. if (_converterList == null)
  281. _converterList = new List<IEnumerable<JavaScriptConverter>> ();
  282. _converterList.Add (converters);
  283. }
  284. internal JavaScriptConverter GetConverter (Type type) {
  285. if (_converterList != null)
  286. for (int i = 0; i < _converterList.Count; i++) {
  287. foreach (JavaScriptConverter converter in _converterList [i])
  288. foreach (Type supportedType in converter.SupportedTypes)
  289. if (supportedType == type)
  290. return converter;
  291. }
  292. return null;
  293. }
  294. public string Serialize (object obj) {
  295. StringBuilder b = new StringBuilder ();
  296. Serialize (obj, b);
  297. return b.ToString ();
  298. }
  299. public void Serialize (object obj, StringBuilder output) {
  300. Serialize (obj, new StringWriter (output));
  301. }
  302. internal void Serialize (object obj, TextWriter output) {
  303. JsonSerializer ser = new JsonSerializer (this);
  304. ser.Serialize (output, obj);
  305. }
  306. }
  307. }