JavaScriptSerializer.cs 10 KB

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