JavaScriptSerializer.cs 6.5 KB

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