JavaScriptSerializer.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. List<IEnumerable<JavaScriptConverter>> _converterList;
  43. public JavaScriptSerializer () {
  44. }
  45. public JavaScriptSerializer (JavaScriptTypeResolver resolver) {
  46. throw new NotImplementedException ();
  47. }
  48. public int MaxJsonLength {
  49. get {
  50. throw new NotImplementedException ();
  51. }
  52. set {
  53. throw new NotImplementedException ();
  54. }
  55. }
  56. public int RecursionLimit {
  57. get {
  58. throw new NotImplementedException ();
  59. }
  60. set {
  61. throw new NotImplementedException ();
  62. }
  63. }
  64. public T ConvertToType<T> (object obj) {
  65. if (obj == null)
  66. return default (T);
  67. return (T) ConvertToType (typeof (T), obj);
  68. }
  69. object ConvertToType (Type type, object obj) {
  70. if (obj == null)
  71. return null;
  72. if (obj is IDictionary<string, object>) {
  73. if (type == null && !(obj is Dictionary<string, object>))
  74. obj = Evaluate ((IDictionary<string, object>) obj);
  75. return Deserialize ((IDictionary<string, object>) obj, type);
  76. }
  77. if (obj is IEnumerable<object>)
  78. return Deserialize ((IEnumerable<object>) obj, type);
  79. if (type == null)
  80. return obj;
  81. Type sourceType = obj.GetType ();
  82. if (type.IsAssignableFrom (sourceType))
  83. return obj;
  84. TypeConverter c = TypeDescriptor.GetConverter (type);
  85. if (c.CanConvertFrom(sourceType)) {
  86. if (obj is string)
  87. return c.ConvertFromInvariantString((string)obj);
  88. return c.ConvertFrom (obj);
  89. }
  90. return Convert.ChangeType (obj, type);
  91. }
  92. public T Deserialize<T> (string input) {
  93. JsonSerializer ser = new JsonSerializer (this);
  94. return ConvertToType<T> (ser.Deserialize (new StringReader (input)));
  95. }
  96. static object Evaluate (object value) {
  97. if (value is IDictionary<string, object>)
  98. value = Evaluate ((IDictionary<string, object>) value);
  99. else
  100. if (value is IEnumerable<object>)
  101. value = Evaluate ((IEnumerable<object>) value);
  102. return value;
  103. }
  104. static object Evaluate (IEnumerable<object> e) {
  105. ArrayList list = new ArrayList ();
  106. foreach (object value in e)
  107. list.Add (Evaluate(value));
  108. return list;
  109. }
  110. static object Evaluate (IDictionary<string, object> dict) {
  111. Dictionary<string, object> d = new Dictionary<string, object> (StringComparer.Ordinal);
  112. foreach (KeyValuePair<string, object> entry in dict)
  113. d.Add (entry.Key, Evaluate(entry.Value));
  114. return d;
  115. }
  116. static readonly Type typeofObject = typeof(object);
  117. static readonly Type typeofGenList = typeof (List<>);
  118. object Deserialize (IEnumerable<object> col, Type type) {
  119. Type elementType = null;
  120. if (type != null && type.HasElementType)
  121. elementType = type.GetElementType ();
  122. IList list;
  123. if (type == null || type.IsArray || typeofObject == type)
  124. list = new ArrayList ();
  125. else if (ReflectionUtils.IsInstantiatableType (type))
  126. // non-generic typed list
  127. list = (IList) Activator.CreateInstance (type, true);
  128. else if (ReflectionUtils.IsAssignable (type, typeofGenList)) {
  129. if (type.IsGenericType) {
  130. Type [] genArgs = type.GetGenericArguments ();
  131. elementType = genArgs [0];
  132. // generic list
  133. list = (IList) Activator.CreateInstance (typeofGenList.MakeGenericType (genArgs));
  134. }
  135. else
  136. list = new ArrayList ();
  137. }
  138. else
  139. throw new JsonSerializationException (string.Format ("Deserializing list type '{0}' not supported.", type.GetType ().Name));
  140. if (list.IsReadOnly) {
  141. Evaluate (col);
  142. return list;
  143. }
  144. foreach (object value in col)
  145. list.Add (ConvertToType (elementType, value));
  146. if (type != null && type.IsArray)
  147. list = ((ArrayList) list).ToArray (elementType);
  148. return list;
  149. }
  150. object Deserialize (IDictionary<string, object> dict, Type type) {
  151. if (type == null)
  152. type = Type.GetType ((string) dict ["__type"]);
  153. object target = Activator.CreateInstance (type, true);
  154. foreach (KeyValuePair<string, object> entry in dict) {
  155. object value = entry.Value;
  156. if (target is IDictionary) {
  157. ((IDictionary) target).Add (entry.Key, ConvertToType (ReflectionUtils.GetTypedDictionaryValueType (type), value));
  158. continue;
  159. }
  160. MemberInfo [] memberCollection = type.GetMember (entry.Key);
  161. if (memberCollection == null || memberCollection.Length == 0) {
  162. //must evaluate value
  163. Evaluate (value);
  164. continue;
  165. }
  166. MemberInfo member = memberCollection [0];
  167. if (!ReflectionUtils.CanSetMemberValue (member)) {
  168. //must evaluate value
  169. Evaluate (value);
  170. continue;
  171. }
  172. ReflectionUtils.SetMemberValue (member, target, ConvertToType(ReflectionUtils.GetMemberUnderlyingType (member), value));
  173. }
  174. return target;
  175. }
  176. public object DeserializeObject (string input) {
  177. throw new NotImplementedException ();
  178. }
  179. public void RegisterConverters (IEnumerable<JavaScriptConverter> converters) {
  180. if (converters == null)
  181. throw new ArgumentNullException ("converters");
  182. if (_converterList == null)
  183. _converterList = new List<IEnumerable<JavaScriptConverter>> ();
  184. _converterList.Add (converters);
  185. }
  186. internal JavaScriptConverter GetConverter (Type type) {
  187. if (_converterList != null)
  188. for (int i = 0; i < _converterList.Count; i++) {
  189. foreach (JavaScriptConverter converter in _converterList [i])
  190. foreach (Type supportedType in converter.SupportedTypes)
  191. if (supportedType == type)
  192. return converter;
  193. }
  194. return null;
  195. }
  196. public string Serialize (object obj) {
  197. StringBuilder b = new StringBuilder ();
  198. Serialize (obj, b);
  199. return b.ToString ();
  200. }
  201. public void Serialize (object obj, StringBuilder output) {
  202. JsonSerializer ser = new JsonSerializer (this);
  203. ser.Serialize (new StringWriter (output), obj);
  204. }
  205. }
  206. }