JsonSerializationReader.cs 13 KB

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