JsonSerializationReader.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. return Type.GetType (name, false);
  137. }
  138. object ReadInstanceDrivenObject ()
  139. {
  140. string type = reader.GetAttribute ("type");
  141. if (type == "object") {
  142. string runtimeType = reader.GetAttribute ("__type");
  143. if (runtimeType != null) {
  144. Type t = GetRuntimeType (runtimeType);
  145. if (t == null)
  146. throw SerializationError (String.Format ("Cannot load type '{0}'", runtimeType));
  147. return ReadObject (t);
  148. }
  149. }
  150. string v = reader.ReadElementContentAsString ();
  151. switch (type) {
  152. case "boolean":
  153. switch (v) {
  154. case "true":
  155. return true;
  156. case "false":
  157. return false;
  158. default:
  159. throw SerializationError (String.Format ("Invalid JSON boolean value: {0}", v));
  160. }
  161. case "string":
  162. return v;
  163. case "null":
  164. if (v != "null")
  165. throw SerializationError (String.Format ("Invalid JSON null value: {0}", v));
  166. return null;
  167. case "number":
  168. int i;
  169. if (int.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out i))
  170. return i;
  171. long l;
  172. if (long.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out l))
  173. return l;
  174. ulong ul;
  175. if (ulong.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out ul))
  176. return ul;
  177. double dbl;
  178. if (double.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dbl))
  179. return dbl;
  180. decimal dec;
  181. if (decimal.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dec))
  182. return dec;
  183. throw SerializationError (String.Format ("Invalid JSON input: {0}", v));
  184. default:
  185. throw SerializationError (String.Format ("Unexpected type: {0}", type));
  186. }
  187. }
  188. string FormatTypeName (Type type)
  189. {
  190. return type.Namespace == null ? type.Name : String.Format ("{0}:#{1}", type.Name, type.Namespace);
  191. }
  192. string ToRuntimeTypeName (string s)
  193. {
  194. int idx = s.IndexOf (":#", StringComparison.Ordinal);
  195. return idx < 0 ? s : String.Concat (s.Substring (idx + 2), ".", s.Substring (0, idx));
  196. }
  197. Type GetCollectionType (Type type)
  198. {
  199. if (type.IsArray)
  200. return type.GetElementType ();
  201. if (type.IsGenericType) {
  202. // returns T for ICollection<T>
  203. Type gt = type.GetGenericTypeDefinition ();
  204. if (gt == typeof (ICollection<>))
  205. return type.GetGenericArguments () [0];
  206. }
  207. if (typeof (IList).IsAssignableFrom (type))
  208. // return typeof(object) for mere collection.
  209. return typeof (object);
  210. else
  211. return null;
  212. }
  213. object DeserializeGenericCollection (Type collectionType, Type elementType)
  214. {
  215. reader.ReadStartElement ();
  216. object ret;
  217. if (typeof (IList).IsAssignableFrom (collectionType)) {
  218. IList c = collectionType.IsArray ?
  219. new ArrayList () :
  220. (IList) Activator.CreateInstance (collectionType);
  221. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  222. if (!reader.IsStartElement ("item"))
  223. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  224. Type et = elementType == typeof (object) || elementType.IsAbstract ? null : elementType;
  225. object elem = ReadObject (et ?? typeof (object));
  226. c.Add (elem);
  227. }
  228. ret = collectionType.IsArray ? ((ArrayList) c).ToArray (elementType) : c;
  229. } else {
  230. object c = Activator.CreateInstance (collectionType);
  231. MethodInfo add = collectionType.GetMethod ("Add", new Type [] {elementType});
  232. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  233. if (!reader.IsStartElement ("item"))
  234. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  235. object elem = ReadObject (elementType);
  236. add.Invoke (c, new object [] {elem});
  237. }
  238. ret = c;
  239. }
  240. reader.ReadEndElement ();
  241. return ret;
  242. }
  243. TypeMap GetTypeMap (Type type)
  244. {
  245. TypeMap map;
  246. if (!typemaps.TryGetValue (type, out map)) {
  247. map = TypeMap.CreateTypeMap (type);
  248. typemaps [type] = map;
  249. }
  250. return map;
  251. }
  252. Exception SerializationError (string basemsg)
  253. {
  254. IXmlLineInfo li = reader as IXmlLineInfo;
  255. if (li == null || !li.HasLineInfo ())
  256. return new SerializationException (basemsg);
  257. else
  258. return new SerializationException (String.Format ("{0}. Error at {1} ({2},{3})", basemsg, reader.BaseURI, li.LineNumber, li.LinePosition));
  259. }
  260. }
  261. }