JsonSerializationReader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. bool isNull = reader.GetAttribute ("type") == "null";
  68. switch (Type.GetTypeCode (type)) {
  69. case TypeCode.DBNull:
  70. string dbn = reader.ReadElementContentAsString ();
  71. if (dbn != String.Empty)
  72. throw new SerializationException (String.Format ("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn));
  73. return DBNull.Value;
  74. case TypeCode.String:
  75. if (isNull) {
  76. reader.ReadElementContentAsString ();
  77. return null;
  78. }
  79. else
  80. return reader.ReadElementContentAsString ();
  81. case TypeCode.Single:
  82. return reader.ReadElementContentAsFloat ();
  83. case TypeCode.Double:
  84. return reader.ReadElementContentAsDouble ();
  85. case TypeCode.Decimal:
  86. return reader.ReadElementContentAsDecimal ();
  87. case TypeCode.Byte:
  88. case TypeCode.SByte:
  89. case TypeCode.Int16:
  90. case TypeCode.Int32:
  91. case TypeCode.UInt16:
  92. case TypeCode.UInt32:
  93. int i = reader.ReadElementContentAsInt ();
  94. if (type.IsEnum)
  95. return Enum.ToObject (type, (object)i);
  96. else
  97. return Convert.ChangeType (i, type, null);
  98. case TypeCode.Int64:
  99. case TypeCode.UInt64:
  100. long l = reader.ReadElementContentAsLong ();
  101. if (type.IsEnum)
  102. return Enum.ToObject (type, (object)l);
  103. else
  104. return Convert.ChangeType (l, type, null);
  105. case TypeCode.Boolean:
  106. return reader.ReadElementContentAsBoolean ();
  107. case TypeCode.DateTime:
  108. // it does not use ReadElementContentAsDateTime(). Different string format.
  109. var s = reader.ReadElementContentAsString ();
  110. if (s.Length < 2 || !s.StartsWith ("/Date(", StringComparison.Ordinal) || !s.EndsWith (")/", StringComparison.Ordinal))
  111. throw new XmlException ("Invalid JSON DateTime format. The value format should be '/Date(UnixTime)/'");
  112. return new DateTime (1970, 1, 1).AddMilliseconds (long.Parse (s.Substring (6, s.Length - 8)));
  113. default:
  114. if (type == typeof (Guid)) {
  115. return new Guid (reader.ReadElementContentAsString ());
  116. } else if (type == typeof (Uri)) {
  117. if (isNull) {
  118. reader.ReadElementContentAsString ();
  119. return null;
  120. }
  121. else
  122. return new Uri (reader.ReadElementContentAsString ());
  123. } else if (type == typeof (XmlQualifiedName)) {
  124. s = reader.ReadElementContentAsString ();
  125. int idx = s.IndexOf (':');
  126. return idx < 0 ? new XmlQualifiedName (s) : new XmlQualifiedName (s.Substring (0, idx), s.Substring (idx + 1));
  127. } else if (type != typeof (object)) {
  128. // strongly-typed object
  129. if (reader.IsEmptyElement) {
  130. // empty -> null array or object
  131. reader.Read ();
  132. return null;
  133. }
  134. Type ct = GetCollectionType (type);
  135. if (ct != null) {
  136. return DeserializeGenericCollection (type, ct);
  137. } else {
  138. TypeMap map = GetTypeMap (type);
  139. return map.Deserialize (this);
  140. }
  141. }
  142. else
  143. return ReadInstanceDrivenObject ();
  144. }
  145. }
  146. Type GetRuntimeType (string name)
  147. {
  148. name = ToRuntimeTypeName (name);
  149. if (serializer.KnownTypes != null)
  150. foreach (Type t in serializer.KnownTypes)
  151. if (t.FullName == name)
  152. return t;
  153. var ret = root_type.Assembly.GetType (name, false) ?? Type.GetType (name, false);
  154. if (ret != null)
  155. return ret;
  156. #if !NET_2_1 // how to do that in ML?
  157. // We probably have to iterate all the existing
  158. // assemblies that are loaded in current domain.
  159. foreach (var ass in AppDomain.CurrentDomain.GetAssemblies ()) {
  160. ret = ass.GetType (name, false);
  161. if (ret != null)
  162. return ret;
  163. }
  164. #endif
  165. return null;
  166. }
  167. object ReadInstanceDrivenObject ()
  168. {
  169. string type = reader.GetAttribute ("type");
  170. if (type == "object") {
  171. string runtimeType = reader.GetAttribute ("__type");
  172. if (runtimeType != null) {
  173. Type t = GetRuntimeType (runtimeType);
  174. if (t == null)
  175. throw SerializationError (String.Format ("Cannot load type '{0}'", runtimeType));
  176. return ReadObject (t);
  177. }
  178. }
  179. string v = reader.ReadElementContentAsString ();
  180. switch (type) {
  181. case "boolean":
  182. switch (v) {
  183. case "true":
  184. return true;
  185. case "false":
  186. return false;
  187. default:
  188. throw SerializationError (String.Format ("Invalid JSON boolean value: {0}", v));
  189. }
  190. case "string":
  191. return v;
  192. case "null":
  193. if (v != "null")
  194. throw SerializationError (String.Format ("Invalid JSON null value: {0}", v));
  195. return null;
  196. case "number":
  197. int i;
  198. if (int.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out i))
  199. return i;
  200. long l;
  201. if (long.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out l))
  202. return l;
  203. ulong ul;
  204. if (ulong.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out ul))
  205. return ul;
  206. double dbl;
  207. if (double.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dbl))
  208. return dbl;
  209. decimal dec;
  210. if (decimal.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dec))
  211. return dec;
  212. throw SerializationError (String.Format ("Invalid JSON input: {0}", v));
  213. default:
  214. throw SerializationError (String.Format ("Unexpected type: {0}", type));
  215. }
  216. }
  217. string FormatTypeName (Type type)
  218. {
  219. return type.Namespace == null ? type.Name : String.Format ("{0}:#{1}", type.Name, type.Namespace);
  220. }
  221. string ToRuntimeTypeName (string s)
  222. {
  223. int idx = s.IndexOf (":#", StringComparison.Ordinal);
  224. return idx < 0 ? s : String.Concat (s.Substring (idx + 2), ".", s.Substring (0, idx));
  225. }
  226. Type GetCollectionType (Type type)
  227. {
  228. if (type.IsArray)
  229. return type.GetElementType ();
  230. if (type.IsGenericType) {
  231. // returns T for ICollection<T>
  232. Type [] ifaces = type.GetInterfaces ();
  233. foreach (Type i in ifaces)
  234. if (i.IsGenericType && i.GetGenericTypeDefinition ().Equals (typeof (ICollection<>)))
  235. return i.GetGenericArguments () [0];
  236. }
  237. if (typeof (IList).IsAssignableFrom (type))
  238. // return typeof(object) for mere collection.
  239. return typeof (object);
  240. else
  241. return null;
  242. }
  243. object DeserializeGenericCollection (Type collectionType, Type elementType)
  244. {
  245. reader.ReadStartElement ();
  246. object ret;
  247. if (collectionType.IsInterface)
  248. collectionType = typeof (List<>).MakeGenericType (elementType);
  249. if (typeof (IList).IsAssignableFrom (collectionType)) {
  250. #if NET_2_1
  251. Type listType = collectionType.IsArray ? typeof (List<>).MakeGenericType (elementType) : null;
  252. #else
  253. Type listType = collectionType.IsArray ? typeof (ArrayList) : null;
  254. #endif
  255. IList c = (IList) Activator.CreateInstance (listType ?? collectionType);
  256. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  257. if (!reader.IsStartElement ("item"))
  258. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  259. Type et = elementType == typeof (object) || elementType.IsAbstract ? null : elementType;
  260. object elem = ReadObject (et ?? typeof (object));
  261. c.Add (elem);
  262. }
  263. #if NET_2_1
  264. if (collectionType.IsArray) {
  265. Array array = Array.CreateInstance (elementType, c.Count);
  266. c.CopyTo (array, 0);
  267. ret = array;
  268. }
  269. else
  270. ret = c;
  271. #else
  272. ret = collectionType.IsArray ? ((ArrayList) c).ToArray (elementType) : c;
  273. #endif
  274. } else {
  275. object c = Activator.CreateInstance (collectionType);
  276. MethodInfo add = collectionType.GetMethod ("Add", new Type [] {elementType});
  277. if (add == null) {
  278. var icoll = typeof (ICollection<>).MakeGenericType (elementType);
  279. if (icoll.IsAssignableFrom (c.GetType ()))
  280. add = icoll.GetMethod ("Add");
  281. }
  282. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  283. if (!reader.IsStartElement ("item"))
  284. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  285. object elem = ReadObject (elementType);
  286. add.Invoke (c, new object [] {elem});
  287. }
  288. ret = c;
  289. }
  290. reader.ReadEndElement ();
  291. return ret;
  292. }
  293. TypeMap GetTypeMap (Type type)
  294. {
  295. TypeMap map;
  296. if (!typemaps.TryGetValue (type, out map)) {
  297. map = TypeMap.CreateTypeMap (type);
  298. typemaps [type] = map;
  299. }
  300. return map;
  301. }
  302. Exception SerializationError (string basemsg)
  303. {
  304. IXmlLineInfo li = reader as IXmlLineInfo;
  305. if (li == null || !li.HasLineInfo ())
  306. return new SerializationException (basemsg);
  307. else
  308. return new SerializationException (String.Format ("{0}. Error at {1} ({2},{3})", basemsg, reader.BaseURI, li.LineNumber, li.LinePosition));
  309. }
  310. }
  311. }