2
0

JsonSerializationReader.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. string typeHint = reader.GetAttribute ("__type");
  172. if (typeHint != null) {
  173. // this might be a derived & known type. We allow it when it's both.
  174. Type exactType = GetRuntimeType (typeHint, type);
  175. if (exactType == null)
  176. throw SerializationError (String.Format ("Cannot load type '{0}'", typeHint));
  177. TypeMap map = GetTypeMap (exactType);
  178. return map.Deserialize (this, instance);
  179. } else { // no type hint
  180. TypeMap map = GetTypeMap (type);
  181. return map.Deserialize (this, instance);
  182. }
  183. }
  184. }
  185. else
  186. return ReadInstanceDrivenObject ();
  187. }
  188. }
  189. object ReadValueType (Type type, bool nullable)
  190. {
  191. string s = reader.ReadElementContentAsString ();
  192. return nullable && s.Trim ().Length == 0 ? null : Convert.ChangeType (s, type, CultureInfo.InvariantCulture);
  193. }
  194. Type GetRuntimeType (string name, Type baseType)
  195. {
  196. string properName = ToRuntimeTypeName (name);
  197. if (baseType != null && baseType.FullName.Equals (properName))
  198. return baseType;
  199. if (serializer.KnownTypes != null)
  200. foreach (Type t in serializer.KnownTypes)
  201. if (t.FullName.Equals (properName))
  202. return t;
  203. if (baseType != null)
  204. foreach (var attr in baseType.GetCustomAttributes (typeof (KnownTypeAttribute), false))
  205. if ((attr as KnownTypeAttribute).Type.FullName.Equals (properName))
  206. return (attr as KnownTypeAttribute).Type;
  207. return null;
  208. }
  209. object ReadInstanceDrivenObject ()
  210. {
  211. string type = reader.GetAttribute ("type");
  212. switch (type) {
  213. case "null":
  214. reader.Skip ();
  215. return null;
  216. case "object":
  217. string runtimeType = reader.GetAttribute ("__type");
  218. if (runtimeType != null) {
  219. Type t = GetRuntimeType (runtimeType, null);
  220. if (t == null)
  221. throw SerializationError (String.Format ("Cannot load type '{0}'", runtimeType));
  222. return ReadObject (t);
  223. }
  224. break;
  225. }
  226. string v = reader.ReadElementContentAsString ();
  227. switch (type) {
  228. case "boolean":
  229. switch (v) {
  230. case "true":
  231. return true;
  232. case "false":
  233. return false;
  234. default:
  235. throw SerializationError (String.Format ("Invalid JSON boolean value: {0}", v));
  236. }
  237. case "string":
  238. return v;
  239. case "number":
  240. int i;
  241. if (int.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out i))
  242. return i;
  243. long l;
  244. if (long.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out l))
  245. return l;
  246. ulong ul;
  247. if (ulong.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out ul))
  248. return ul;
  249. double dbl;
  250. if (double.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dbl))
  251. return dbl;
  252. decimal dec;
  253. if (decimal.TryParse (v, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dec))
  254. return dec;
  255. throw SerializationError (String.Format ("Invalid JSON input: {0}", v));
  256. default:
  257. throw SerializationError (String.Format ("Unexpected type: {0}", type));
  258. }
  259. }
  260. string FormatTypeName (Type type)
  261. {
  262. return type.Namespace == null ? type.Name : String.Format ("{0}:#{1}", type.Name, type.Namespace);
  263. }
  264. string ToRuntimeTypeName (string s)
  265. {
  266. int idx = s.IndexOf (":#", StringComparison.Ordinal);
  267. return idx < 0 ? s : String.Concat (s.Substring (idx + 2), ".", s.Substring (0, idx));
  268. }
  269. Type GetCollectionElementType (Type type)
  270. {
  271. if (type.IsArray)
  272. return type.GetElementType ();
  273. if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (IEnumerable<>))
  274. return type.GetGenericArguments () [0];
  275. var inter = type.GetInterface ("System.Collections.Generic.IEnumerable`1", false);
  276. if (inter != null)
  277. return inter.GetGenericArguments () [0];
  278. if (typeof (IEnumerable).IsAssignableFrom (type))
  279. // return typeof(object) for mere collection.
  280. return typeof (object);
  281. else
  282. return null;
  283. }
  284. object DeserializeGenericCollection (Type collectionType, Type elementType, object collectionInstance)
  285. {
  286. reader.ReadStartElement ();
  287. object ret;
  288. if (collectionType.IsInterface)
  289. collectionType = typeof (List<>).MakeGenericType (elementType);
  290. if (TypeMap.IsDictionary (collectionType)) {
  291. if (collectionInstance == null)
  292. collectionInstance = Activator.CreateInstance (collectionType);
  293. var keyType = elementType.IsGenericType ? elementType.GetGenericArguments () [0] : typeof (object);
  294. var valueType = elementType.IsGenericType ? elementType.GetGenericArguments () [1] : typeof (object);
  295. MethodInfo add = collectionType.GetMethod ("Add", new Type [] { keyType, valueType });
  296. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  297. if (!reader.IsStartElement ("item"))
  298. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  299. // reading a KeyValuePair in the form of <Key .../><Value .../>
  300. reader.Read ();
  301. reader.MoveToContent ();
  302. object key = ReadObject (keyType);
  303. reader.MoveToContent ();
  304. object val = ReadObject (valueType);
  305. reader.Read ();
  306. add.Invoke (collectionInstance, new [] { key, val });
  307. }
  308. ret = collectionInstance;
  309. } else if (typeof (IList).IsAssignableFrom (collectionType)) {
  310. #if NET_2_1
  311. Type listType = collectionType.IsArray ? typeof (List<>).MakeGenericType (elementType) : null;
  312. #else
  313. Type listType = collectionType.IsArray ? typeof (ArrayList) : null;
  314. #endif
  315. IList c;
  316. if (collectionInstance == null)
  317. c = (IList) Activator.CreateInstance (listType ?? collectionType);
  318. else
  319. c = (IList) collectionInstance;
  320. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  321. if (!reader.IsStartElement ("item"))
  322. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  323. object elem = ReadObject (elementType);
  324. c.Add (elem);
  325. }
  326. #if NET_2_1
  327. if (collectionType.IsArray) {
  328. Array array = Array.CreateInstance (elementType, c.Count);
  329. c.CopyTo (array, 0);
  330. ret = array;
  331. }
  332. else
  333. ret = c;
  334. #else
  335. ret = collectionType.IsArray ? ((ArrayList) c).ToArray (elementType) : c;
  336. #endif
  337. } else {
  338. if (collectionInstance == null)
  339. collectionInstance = Activator.CreateInstance (collectionType);
  340. MethodInfo add;
  341. if (collectionInstance.GetType ().IsGenericType &&
  342. collectionInstance.GetType ().GetGenericTypeDefinition () == typeof (LinkedList<>))
  343. add = collectionType.GetMethod ("AddLast", new Type [] { elementType });
  344. else
  345. add = collectionType.GetMethod ("Add", new Type [] { elementType });
  346. if (add == null) {
  347. var icoll = typeof (ICollection<>).MakeGenericType (elementType);
  348. if (icoll.IsAssignableFrom (collectionInstance.GetType ()))
  349. add = icoll.GetMethod ("Add");
  350. }
  351. if (add == null)
  352. throw new MissingMethodException (elementType.FullName, "Add");
  353. for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
  354. if (!reader.IsStartElement ("item"))
  355. throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
  356. object element = ReadObject (elementType);
  357. add.Invoke (collectionInstance, new object [] { element });
  358. }
  359. ret = collectionInstance;
  360. }
  361. reader.ReadEndElement ();
  362. return ret;
  363. }
  364. TypeMap GetTypeMap (Type type)
  365. {
  366. TypeMap map;
  367. if (!typemaps.TryGetValue (type, out map)) {
  368. map = TypeMap.CreateTypeMap (type);
  369. typemaps [type] = map;
  370. }
  371. return map;
  372. }
  373. Exception SerializationError (string basemsg)
  374. {
  375. IXmlLineInfo li = reader as IXmlLineInfo;
  376. if (li == null || !li.HasLineInfo ())
  377. return new SerializationException (basemsg);
  378. else
  379. return new SerializationException (String.Format ("{0}. Error at {1} ({2},{3})", basemsg, reader.BaseURI, li.LineNumber, li.LinePosition));
  380. }
  381. }
  382. }