JavaScriptSerializer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. /*
  171. * Take care of the special case whereas in JSON an empty string ("") really means
  172. * an empty value
  173. * (see: https://bugzilla.novell.com/show_bug.cgi?id=328836)
  174. */
  175. if ( (type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Nullable<>)) )
  176. {
  177. string s = obj as String;
  178. if (String.IsNullOrEmpty(s))
  179. return null;
  180. }
  181. if (type == null)
  182. return obj;
  183. Type sourceType = obj.GetType ();
  184. if (type.IsAssignableFrom (sourceType))
  185. return obj;
  186. if (type.IsEnum)
  187. return Enum.ToObject (type, obj);
  188. TypeConverter c = TypeDescriptor.GetConverter (type);
  189. if (c.CanConvertFrom (sourceType)) {
  190. if (obj is string)
  191. return c.ConvertFromInvariantString ((string) obj);
  192. return c.ConvertFrom (obj);
  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. if (value is IDictionary<string, object>)
  201. value = EvaluateDictionary ((IDictionary<string, object>) value);
  202. else
  203. if (value is IEnumerable<object>)
  204. value = EvaluateList ((IEnumerable<object>) value);
  205. return value;
  206. }
  207. static object EvaluateList (IEnumerable<object> e) {
  208. ArrayList list = new ArrayList ();
  209. foreach (object value in e)
  210. list.Add (Evaluate(value));
  211. return list.ToArray ();
  212. }
  213. static IDictionary<string, object> EvaluateDictionary (IDictionary<string, object> dict) {
  214. if (dict is Dictionary<string, object>)
  215. return dict;
  216. Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
  217. foreach (KeyValuePair<string, object> entry in dict) {
  218. d.Add (entry.Key, Evaluate (entry.Value));
  219. }
  220. return d;
  221. }
  222. static readonly Type typeofObject = typeof(object);
  223. static readonly Type typeofGenList = typeof (List<>);
  224. object ConvertToList (IEnumerable<object> col, Type type) {
  225. Type elementType = null;
  226. if (type != null && type.HasElementType)
  227. elementType = type.GetElementType ();
  228. IList list;
  229. if (type == null || type.IsArray || typeofObject == type)
  230. list = new ArrayList ();
  231. else if (ReflectionUtils.IsInstantiatableType (type))
  232. // non-generic typed list
  233. list = (IList) Activator.CreateInstance (type, true);
  234. else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
  235. if (type.IsGenericType) {
  236. Type [] genArgs = type.GetGenericArguments ();
  237. elementType = genArgs [0];
  238. // generic list
  239. list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
  240. }
  241. else
  242. list = new ArrayList ();
  243. }
  244. else
  245. throw new JsonSerializationException (string.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
  246. if (list.IsReadOnly) {
  247. EvaluateList (col);
  248. return list;
  249. }
  250. foreach (object value in col)
  251. list.Add (ConvertToType (elementType, value));
  252. if (type != null && type.IsArray)
  253. list = ((ArrayList) list).ToArray (elementType);
  254. return list;
  255. }
  256. object ConvertToObject (IDictionary<string, object> dict, Type type)
  257. {
  258. if (_typeResolver != null) {
  259. if (dict is JsonSerializer.DeserializerLazyDictionary) {
  260. JsonSerializer.DeserializerLazyDictionary lazyDict = (JsonSerializer.DeserializerLazyDictionary) dict;
  261. object first = lazyDict.PeekFirst ();
  262. if (first != null) {
  263. KeyValuePair<string, object> firstPair = (KeyValuePair<string, object>) first;
  264. if (firstPair.Key == SerializedTypeNameKey) {
  265. type = _typeResolver.ResolveType ((string) firstPair.Value);
  266. }
  267. else {
  268. dict = EvaluateDictionary (dict);
  269. }
  270. }
  271. }
  272. if (!(dict is JsonSerializer.DeserializerLazyDictionary) && dict.Keys.Contains(SerializedTypeNameKey)) {
  273. // already Evaluated
  274. type = _typeResolver.ResolveType ((string) dict [SerializedTypeNameKey]);
  275. }
  276. }
  277. object target = Activator.CreateInstance (type, true);
  278. foreach (KeyValuePair<string, object> entry in dict) {
  279. object value = entry.Value;
  280. if (target is IDictionary) {
  281. ((IDictionary) target).Add (entry.Key, ConvertToType (ReflectionUtils.GetTypedDictionaryValueType (type), value));
  282. continue;
  283. }
  284. MemberInfo [] memberCollection = type.GetMember (entry.Key);
  285. if (memberCollection == null || memberCollection.Length == 0) {
  286. //must evaluate value
  287. Evaluate (value);
  288. continue;
  289. }
  290. MemberInfo member = memberCollection [0];
  291. if (!ReflectionUtils.CanSetMemberValue (member)) {
  292. //must evaluate value
  293. Evaluate (value);
  294. continue;
  295. }
  296. ReflectionUtils.SetMemberValue (member, target, ConvertToType(ReflectionUtils.GetMemberUnderlyingType (member), value));
  297. }
  298. return target;
  299. }
  300. public object DeserializeObject (string input) {
  301. object obj = Evaluate (DeserializeObjectInternal (new StringReader (input)));
  302. IDictionary dictObj = obj as IDictionary;
  303. if (dictObj != null && dictObj.Contains(SerializedTypeNameKey)){
  304. if (_typeResolver == null) {
  305. throw new ArgumentNullException ("resolver", "Must have a type resolver to deserialize an object that has an '__type' member");
  306. }
  307. obj = ConvertToType(null, obj);
  308. }
  309. return obj;
  310. }
  311. internal object DeserializeObjectInternal (string input) {
  312. return DeserializeObjectInternal (new StringReader (input));
  313. }
  314. internal object DeserializeObjectInternal (TextReader input) {
  315. JsonSerializer ser = new JsonSerializer (this, _typeResolver);
  316. ser.MaxJsonLength = MaxJsonLength;
  317. ser.RecursionLimit = RecursionLimit;
  318. return ser.Deserialize (input);
  319. }
  320. public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
  321. if (converters == null)
  322. throw new ArgumentNullException ("converters");
  323. if (_converterList == null)
  324. _converterList = new List<IEnumerable<JavaScriptConverter>> ();
  325. _converterList.Add (converters);
  326. }
  327. internal JavaScriptConverter GetConverter (Type type) {
  328. if (_converterList != null)
  329. for (int i = 0; i < _converterList.Count; i++) {
  330. foreach (JavaScriptConverter converter in _converterList [i])
  331. foreach (Type supportedType in converter.SupportedTypes)
  332. if (supportedType == type)
  333. return converter;
  334. }
  335. return null;
  336. }
  337. public string Serialize (object obj) {
  338. StringBuilder b = new StringBuilder ();
  339. Serialize (obj, b);
  340. return b.ToString ();
  341. }
  342. public void Serialize (object obj, StringBuilder output) {
  343. Serialize (obj, new StringWriter (output));
  344. }
  345. internal void Serialize (object obj, TextWriter output) {
  346. JsonSerializer ser = new JsonSerializer (this, _typeResolver);
  347. ser.MaxJsonLength = MaxJsonLength;
  348. ser.RecursionLimit = RecursionLimit;
  349. ser.Serialize (output, obj);
  350. }
  351. }
  352. }