JsonSerializationReader.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. //
  2. // JsonSerializationReader.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Collections.ObjectModel;
  32. using System.Globalization;
  33. using System.IO;
  34. using System.Reflection;
  35. using System.Text;
  36. using System.Xml;
  37. namespace System.Runtime.Serialization.Json
  38. {
  39. class JsonSerializationReader
  40. {
  41. DataContractJsonSerializer serializer;
  42. XmlReader reader;
  43. int serialized_object_count;
  44. bool verify_object_name;
  45. Dictionary<Type, TypeMap> typemaps = new Dictionary<Type, TypeMap> ();
  46. Type root_type;
  47. public JsonSerializationReader (DataContractJsonSerializer serializer, XmlReader reader, Type rootType, bool verifyObjectName)
  48. {
  49. this.serializer = serializer;
  50. this.reader = reader;
  51. this.root_type = rootType;
  52. this.verify_object_name = verifyObjectName;
  53. }
  54. public XmlReader Reader {
  55. get { return reader; }
  56. }
  57. public object ReadRoot ()
  58. {
  59. TypeMap rootMap = GetTypeMap (root_type);
  60. object v = ReadObject (root_type);
  61. return v;
  62. }
  63. public object ReadObject (Type type)
  64. {
  65. if (serialized_object_count ++ == serializer.MaxItemsInObjectGraph)
  66. throw SerializationError (String.Format ("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph));
  67. switch (Type.GetTypeCode (type)) {
  68. case TypeCode.DBNull:
  69. string dbn = reader.ReadElementContentAsString ();
  70. if (dbn != String.Empty)
  71. throw new SerializationException (String.Format ("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn));
  72. return DBNull.Value;
  73. case TypeCode.String:
  74. return reader.ReadElementContentAsString ();
  75. case TypeCode.Single:
  76. return reader.ReadElementContentAsFloat ();
  77. case TypeCode.Double:
  78. return reader.ReadElementContentAsDouble ();
  79. case TypeCode.Decimal:
  80. return reader.ReadElementContentAsDecimal ();
  81. case TypeCode.Byte:
  82. case TypeCode.SByte:
  83. case TypeCode.Int16:
  84. case TypeCode.Int32:
  85. case TypeCode.UInt16:
  86. case TypeCode.UInt32:
  87. int i = reader.ReadElementContentAsInt ();
  88. if (type.IsEnum)
  89. return Enum.ToObject (type, (object)i);
  90. else
  91. return Convert.ChangeType (i, type, null);
  92. case TypeCode.Int64:
  93. case TypeCode.UInt64:
  94. long l = reader.ReadElementContentAsLong ();
  95. if (type.IsEnum)
  96. return Enum.ToObject (type, (object)l);
  97. else
  98. return Convert.ChangeType (l, type, null);
  99. case TypeCode.Boolean:
  100. return reader.ReadElementContentAsBoolean ();
  101. default:
  102. if (type == typeof (Guid)) {
  103. return new Guid (reader.ReadElementContentAsString ());
  104. } else if (type == typeof (Uri)) {
  105. return new Uri (reader.ReadElementContentAsString ());
  106. } else if (type == typeof (XmlQualifiedName)) {
  107. string s = reader.ReadElementContentAsString ();
  108. int idx = s.IndexOf (':');
  109. return idx < 0 ? new XmlQualifiedName (s) : new XmlQualifiedName (s.Substring (0, idx), s.Substring (idx + 1));
  110. } else if (type != typeof (object)) {
  111. // strongly-typed object
  112. if (reader.IsEmptyElement) {
  113. // empty -> null array or object
  114. reader.Read ();
  115. return null;
  116. }
  117. Type ct = GetCollectionType (type);
  118. if (ct != null) {
  119. return DeserializeGenericCollection (type, ct);
  120. } else {
  121. TypeMap map = GetTypeMap (type);
  122. return map.Deserialize (this);
  123. }
  124. }
  125. else
  126. return ReadInstanceDrivenObject ();
  127. }
  128. }
  129. Type GetRuntimeType (string name)
  130. {
  131. name = ToRuntimeTypeName (name);
  132. if (serializer.KnownTypes != null)
  133. foreach (Type t in serializer.KnownTypes)
  134. if (t.FullName == name)
  135. return t;
  136. var ret = root_type.Assembly.GetType (name, false) ?? Type.GetType (name, false);
  137. if (ret != null)
  138. return ret;
  139. #if !NET_2_1 // how to do that in ML?
  140. // We probably have to iterate all the existing
  141. // assemblies that are loaded in current domain.
  142. foreach (var ass in AppDomain.CurrentDomain.GetAssemblies ()) {
  143. ret = ass.GetType (name, false);
  144. if (ret != null)
  145. return ret;
  146. }
  147. #endif
  148. return null;
  149. }
  150. object ReadInstanceDrivenObject ()
  151. {
  152. string type = reader.GetAttribute ("type");
  153. if (type == "object") {
  154. string runtimeType = reader.GetAttribute ("__type");
  155. if (runtimeType != null) {
  156. Type t = GetRuntimeType (runtimeType);
  157. if (t == null)
  158. throw SerializationError (String.Format ("Cannot load type '{0}'", runtimeType));
  159. return ReadObject (t);
  160. }
  161. }
  162. string v = reader.ReadElementContentAsString ();
  163. switch (type) {
  164. case "boolean":
  165. switch (v) {
  166. case "true":
  167. return true;
  168. case "false":
  169. return false;
  170. default:
  171. throw SerializationError (String.Format ("Invalid JSON boolean value: {0}", v));
  172. }
  173. case "string":
  174. return v;
  175. case "null":
  176. if (v != "null")
  177. throw SerializationError (String.Format ("Invalid JSON null value: {0}", v));
  178. return null;
  179. case "number":
  180. int i;
  181. if (int.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out i))
  182. return i;
  183. long l;
  184. if (long.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out l))
  185. return l;
  186. ulong ul;
  187. if (ulong.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out ul))
  188. return ul;
  189. double dbl;
  190. if (double.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dbl))
  191. return dbl;
  192. decimal dec;
  193. if (decimal.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dec))
  194. return dec;
  195. throw SerializationError (String.Format ("Invalid JSON input: {0}", v));
  196. default:
  197. throw SerializationError (String.Format ("Unexpected type: {0}", type));
  198. }
  199. }
  200. string FormatTypeName (Type type)
  201. {
  202. return type.Namespace == null ? type.Name : String.Format ("{0}:#{1}", type.Name, type.Namespace);
  203. }
  204. string ToRuntimeTypeName (string s)
  205. {
  206. int idx = s.IndexOf (":#", StringComparison.Ordinal);
  207. return idx < 0 ? s : String.Concat (s.Substring (idx + 2), ".", s.Substring (0, idx));
  208. }
  209. Type GetCollectionType (Type type)
  210. {
  211. if (type.IsArray)
  212. return type.GetElementType ();
  213. if (type.IsGenericType) {
  214. // returns T for ICollection<T>
  215. Type [] ifaces = type.GetInterfaces ();
  216. foreach (Type i in ifaces)
  217. if (i.IsGenericType && i.GetGenericTypeDefinition ().Equals (typeof (ICollection<>)))
  218. return i.GetGenericArguments () [0];
  219. }
  220. if (typeof (IList).IsAssignableFrom (type))
  221. // return typeof(object) for mere collection.
  222. return typeof (object);
  223. else
  224. return null;
  225. }
  226. object DeserializeGenericCollection (Type collectionType, Type elementType)
  227. {
  228. reader.ReadStartElement ();
  229. object ret;
  230. if (typeof (IList).IsAssignableFrom (collectionType)) {
  231. #if NET_2_1
  232. Type listType = collectionType.IsArray ? typeof (List<>).MakeGenericType (elementType) : null;
  233. #else
  234. Type listType = collectionType.IsArray ? typeof (ArrayList) : null;
  235. #endif
  236. IList c = (IList) Activator.CreateInstance (listType ?? collectionType);
  237. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  238. if (!reader.IsStartElement ("item"))
  239. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  240. Type et = elementType == typeof (object) || elementType.IsAbstract ? null : elementType;
  241. object elem = ReadObject (et ?? typeof (object));
  242. c.Add (elem);
  243. }
  244. #if NET_2_1
  245. if (collectionType.IsArray) {
  246. Array array = Array.CreateInstance (elementType, c.Count);
  247. c.CopyTo (array, 0);
  248. ret = array;
  249. }
  250. else
  251. ret = c;
  252. #else
  253. ret = collectionType.IsArray ? ((ArrayList) c).ToArray (elementType) : c;
  254. #endif
  255. } else {
  256. object c = Activator.CreateInstance (collectionType);
  257. MethodInfo add = collectionType.GetMethod ("Add", new Type [] {elementType});
  258. if (add == null) {
  259. var icoll = typeof (ICollection<>).MakeGenericType (elementType);
  260. if (icoll.IsAssignableFrom (c.GetType ()))
  261. add = icoll.GetMethod ("Add");
  262. }
  263. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  264. if (!reader.IsStartElement ("item"))
  265. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  266. object elem = ReadObject (elementType);
  267. add.Invoke (c, new object [] {elem});
  268. }
  269. ret = c;
  270. }
  271. reader.ReadEndElement ();
  272. return ret;
  273. }
  274. TypeMap GetTypeMap (Type type)
  275. {
  276. TypeMap map;
  277. if (!typemaps.TryGetValue (type, out map)) {
  278. map = TypeMap.CreateTypeMap (type);
  279. typemaps [type] = map;
  280. }
  281. return map;
  282. }
  283. Exception SerializationError (string basemsg)
  284. {
  285. IXmlLineInfo li = reader as IXmlLineInfo;
  286. if (li == null || !li.HasLineInfo ())
  287. return new SerializationException (basemsg);
  288. else
  289. return new SerializationException (String.Format ("{0}. Error at {1} ({2},{3})", basemsg, reader.BaseURI, li.LineNumber, li.LinePosition));
  290. }
  291. }
  292. }