JsonSerializationReader.cs 14 KB

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