JavaScriptSerializer.cs 11 KB

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