2
0

JsonSerializationReader.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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.Linq;
  35. using System.Reflection;
  36. using System.Text;
  37. using System.Xml;
  38. namespace System.Runtime.Serialization.Json
  39. {
  40. class JsonSerializationReader
  41. {
  42. DataContractJsonSerializer serializer;
  43. XmlReader reader;
  44. int serialized_object_count;
  45. bool verify_object_name;
  46. Dictionary<Type, TypeMap> typemaps = new Dictionary<Type, TypeMap> ();
  47. Type root_type;
  48. public JsonSerializationReader (DataContractJsonSerializer serializer, XmlReader reader, Type rootType, bool verifyObjectName)
  49. {
  50. this.serializer = serializer;
  51. this.reader = reader;
  52. this.root_type = rootType;
  53. this.verify_object_name = verifyObjectName;
  54. }
  55. public XmlReader Reader {
  56. get { return reader; }
  57. }
  58. public object ReadRoot ()
  59. {
  60. TypeMap rootMap = GetTypeMap (root_type);
  61. object v = ReadObject (root_type);
  62. return v;
  63. }
  64. public object ReadObject (Type type)
  65. {
  66. if (serialized_object_count ++ == serializer.MaxItemsInObjectGraph)
  67. throw SerializationError (String.Format ("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph));
  68. bool nullable = false;
  69. if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>)) {
  70. nullable = true;
  71. type = Nullable.GetUnderlyingType (type);
  72. }
  73. bool isNull = reader.GetAttribute ("type") == "null";
  74. switch (Type.GetTypeCode (type)) {
  75. case TypeCode.DBNull:
  76. string dbn = reader.ReadElementContentAsString ();
  77. if (dbn != String.Empty)
  78. throw new SerializationException (String.Format ("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn));
  79. return DBNull.Value;
  80. case TypeCode.String:
  81. if (isNull) {
  82. reader.ReadElementContentAsString ();
  83. return null;
  84. }
  85. else
  86. return reader.ReadElementContentAsString ();
  87. case TypeCode.Char:
  88. var c = reader.ReadElementContentAsString ();
  89. if (c.Length > 1)
  90. throw new XmlException ("Invalid JSON char");
  91. return Char.Parse(c);
  92. case TypeCode.Single:
  93. return reader.ReadElementContentAsFloat ();
  94. case TypeCode.Double:
  95. return reader.ReadElementContentAsDouble ();
  96. case TypeCode.Decimal:
  97. return reader.ReadElementContentAsDecimal ();
  98. case TypeCode.Byte:
  99. case TypeCode.SByte:
  100. case TypeCode.Int16:
  101. case TypeCode.Int32:
  102. case TypeCode.UInt16:
  103. if (type.IsEnum)
  104. return Enum.ToObject (type, Convert.ChangeType (reader.ReadElementContentAsLong (), Enum.GetUnderlyingType (type), null));
  105. else
  106. return Convert.ChangeType (reader.ReadElementContentAsDecimal (), type, null);
  107. case TypeCode.UInt32:
  108. case TypeCode.Int64:
  109. case TypeCode.UInt64:
  110. if (type.IsEnum)
  111. return Enum.ToObject (type, Convert.ChangeType (reader.ReadElementContentAsLong (), Enum.GetUnderlyingType (type), null));
  112. else
  113. return Convert.ChangeType (reader.ReadElementContentAsDecimal (), type, null);
  114. case TypeCode.Boolean:
  115. return reader.ReadElementContentAsBoolean ();
  116. case TypeCode.DateTime:
  117. // it does not use ReadElementContentAsDateTime(). Different string format.
  118. var s = reader.ReadElementContentAsString ();
  119. if (s.Length < 2 || !s.StartsWith ("/Date(", StringComparison.Ordinal) || !s.EndsWith (")/", StringComparison.Ordinal)) {
  120. if (nullable)
  121. return null;
  122. throw new XmlException ("Invalid JSON DateTime format. The value format should be '/Date(UnixTime)/'");
  123. }
  124. // The date can contain [SIGN]LONG, [SIGN]LONG+HOURSMINUTES or [SIGN]LONG-HOURSMINUTES
  125. // the format for HOURSMINUTES is DDDD
  126. int tidx = s.IndexOf ('-', 8);
  127. if (tidx == -1)
  128. tidx = s.IndexOf ('+', 8);
  129. int minutes = 0;
  130. if (tidx == -1){
  131. s = s.Substring (6, s.Length - 8);
  132. } else {
  133. int offset;
  134. int.TryParse (s.Substring (tidx+1, s.Length-3-tidx), out offset);
  135. minutes = (offset % 100) + (offset / 100) * 60;
  136. if (s [tidx] == '-')
  137. minutes = -minutes;
  138. s = s.Substring (6, tidx-6);
  139. }
  140. var date = new DateTime (1970, 1, 1).AddMilliseconds (long.Parse (s));
  141. if (minutes != 0)
  142. date = date.AddMinutes (minutes);
  143. return date;
  144. default:
  145. if (type == typeof (Guid)) {
  146. return new Guid (reader.ReadElementContentAsString ());
  147. } else if (type == typeof (Uri)) {
  148. if (isNull) {
  149. reader.ReadElementContentAsString ();
  150. return null;
  151. }
  152. else
  153. return new Uri (reader.ReadElementContentAsString ());
  154. } else if (type == typeof (XmlQualifiedName)) {
  155. s = reader.ReadElementContentAsString ();
  156. int idx = s.IndexOf (':');
  157. return idx < 0 ? new XmlQualifiedName (s) : new XmlQualifiedName (s.Substring (0, idx), s.Substring (idx + 1));
  158. } else if (type != typeof (object)) {
  159. // strongly-typed object
  160. if (reader.IsEmptyElement) {
  161. // empty -> null array or object
  162. reader.Read ();
  163. return null;
  164. }
  165. Type ct = GetCollectionElementType (type);
  166. if (ct != null) {
  167. return DeserializeGenericCollection (type, ct);
  168. } else {
  169. TypeMap map = GetTypeMap (type);
  170. return map.Deserialize (this);
  171. }
  172. }
  173. else
  174. return ReadInstanceDrivenObject ();
  175. }
  176. }
  177. Type GetRuntimeType (string name)
  178. {
  179. name = ToRuntimeTypeName (name);
  180. if (serializer.KnownTypes != null)
  181. foreach (Type t in serializer.KnownTypes)
  182. if (t.FullName == name)
  183. return t;
  184. var ret = root_type.Assembly.GetType (name, false) ?? Type.GetType (name, false);
  185. if (ret != null)
  186. return ret;
  187. // We probably have to iterate all the existing
  188. // assemblies that are loaded in current domain.
  189. foreach (var ass in AppDomain.CurrentDomain.GetAssemblies ()) {
  190. ret = ass.GetType (name, false);
  191. if (ret != null)
  192. return ret;
  193. }
  194. return null;
  195. }
  196. object ReadInstanceDrivenObject ()
  197. {
  198. string type = reader.GetAttribute ("type");
  199. switch (type) {
  200. case "null":
  201. reader.Skip ();
  202. return null;
  203. case "object":
  204. string runtimeType = reader.GetAttribute ("__type");
  205. if (runtimeType != null) {
  206. Type t = GetRuntimeType (runtimeType);
  207. if (t == null)
  208. throw SerializationError (String.Format ("Cannot load type '{0}'", runtimeType));
  209. return ReadObject (t);
  210. }
  211. break;
  212. }
  213. string v = reader.ReadElementContentAsString ();
  214. switch (type) {
  215. case "boolean":
  216. switch (v) {
  217. case "true":
  218. return true;
  219. case "false":
  220. return false;
  221. default:
  222. throw SerializationError (String.Format ("Invalid JSON boolean value: {0}", v));
  223. }
  224. case "string":
  225. return v;
  226. case "number":
  227. int i;
  228. if (int.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out i))
  229. return i;
  230. long l;
  231. if (long.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out l))
  232. return l;
  233. ulong ul;
  234. if (ulong.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out ul))
  235. return ul;
  236. double dbl;
  237. if (double.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dbl))
  238. return dbl;
  239. decimal dec;
  240. if (decimal.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dec))
  241. return dec;
  242. throw SerializationError (String.Format ("Invalid JSON input: {0}", v));
  243. default:
  244. throw SerializationError (String.Format ("Unexpected type: {0}", type));
  245. }
  246. }
  247. string FormatTypeName (Type type)
  248. {
  249. return type.Namespace == null ? type.Name : String.Format ("{0}:#{1}", type.Name, type.Namespace);
  250. }
  251. string ToRuntimeTypeName (string s)
  252. {
  253. int idx = s.IndexOf (":#", StringComparison.Ordinal);
  254. return idx < 0 ? s : String.Concat (s.Substring (idx + 2), ".", s.Substring (0, idx));
  255. }
  256. IEnumerable<Type> GetInterfaces2 (Type type)
  257. {
  258. if (type.IsInterface)
  259. yield return type;
  260. foreach (var t in type.GetInterfaces ())
  261. yield return t;
  262. }
  263. Type GetCollectionElementType (Type type)
  264. {
  265. if (type.IsArray)
  266. return type.GetElementType ();
  267. if (type.IsGenericType) {
  268. // returns T for IEnumerable<T>
  269. foreach (Type i in GetInterfaces2 (type))
  270. if (i.IsGenericType && i.GetGenericTypeDefinition ().Equals (typeof (IEnumerable<>)))
  271. return i.GetGenericArguments () [0];
  272. }
  273. if (typeof (IEnumerable).IsAssignableFrom (type))
  274. // return typeof(object) for mere collection.
  275. return typeof (object);
  276. else
  277. return null;
  278. }
  279. object DeserializeGenericCollection (Type collectionType, Type elementType)
  280. {
  281. reader.ReadStartElement ();
  282. object ret;
  283. if (collectionType.IsInterface)
  284. collectionType = typeof (List<>).MakeGenericType (elementType);
  285. if (TypeMap.IsDictionary (collectionType)) {
  286. object dic = Activator.CreateInstance (collectionType);
  287. var itemSetter = dic.GetType ().GetProperty ("Item");
  288. var keyarr = new object [1];
  289. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  290. if (!reader.IsStartElement ("item"))
  291. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  292. // reading a KeyValuePair in the form of <Key .../><Value .../>
  293. reader.Read ();
  294. reader.MoveToContent ();
  295. object key = ReadObject (elementType.GetGenericArguments () [0]);
  296. reader.MoveToContent ();
  297. object val = ReadObject (elementType.GetGenericArguments () [1]);
  298. reader.Read ();
  299. keyarr [0] = key;
  300. itemSetter.SetValue (dic, val, keyarr);
  301. }
  302. ret = dic;
  303. } else if (typeof (IList).IsAssignableFrom (collectionType)) {
  304. #if NET_2_1
  305. Type listType = collectionType.IsArray ? typeof (List<>).MakeGenericType (elementType) : null;
  306. #else
  307. Type listType = collectionType.IsArray ? typeof (ArrayList) : null;
  308. #endif
  309. IList c = (IList) Activator.CreateInstance (listType ?? collectionType);
  310. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  311. if (!reader.IsStartElement ("item"))
  312. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  313. Type et = elementType == typeof (object) || elementType.IsAbstract ? null : elementType;
  314. object elem = ReadObject (et ?? typeof (object));
  315. c.Add (elem);
  316. }
  317. #if NET_2_1
  318. if (collectionType.IsArray) {
  319. Array array = Array.CreateInstance (elementType, c.Count);
  320. c.CopyTo (array, 0);
  321. ret = array;
  322. }
  323. else
  324. ret = c;
  325. #else
  326. ret = collectionType.IsArray ? ((ArrayList) c).ToArray (elementType) : c;
  327. #endif
  328. } else {
  329. object c = Activator.CreateInstance (collectionType);
  330. MethodInfo add = collectionType.GetMethod ("Add", new Type [] {elementType});
  331. if (add == null) {
  332. var icoll = typeof (ICollection<>).MakeGenericType (elementType);
  333. if (icoll.IsAssignableFrom (c.GetType ()))
  334. add = icoll.GetMethod ("Add");
  335. }
  336. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  337. if (!reader.IsStartElement ("item"))
  338. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  339. object elem = ReadObject (elementType);
  340. add.Invoke (c, new object [] {elem});
  341. }
  342. ret = c;
  343. }
  344. reader.ReadEndElement ();
  345. return ret;
  346. }
  347. TypeMap GetTypeMap (Type type)
  348. {
  349. TypeMap map;
  350. if (!typemaps.TryGetValue (type, out map)) {
  351. map = TypeMap.CreateTypeMap (type);
  352. typemaps [type] = map;
  353. }
  354. return map;
  355. }
  356. Exception SerializationError (string basemsg)
  357. {
  358. IXmlLineInfo li = reader as IXmlLineInfo;
  359. if (li == null || !li.HasLineInfo ())
  360. return new SerializationException (basemsg);
  361. else
  362. return new SerializationException (String.Format ("{0}. Error at {1} ({2},{3})", basemsg, reader.BaseURI, li.LineNumber, li.LinePosition));
  363. }
  364. }
  365. }