DataContractJsonSerializer.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. //
  2. // DataContractJsonSerializer.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2007-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. public sealed class DataContractJsonSerializer : XmlObjectSerializer
  41. {
  42. const string default_root_name = "root";
  43. #region lengthy constructor list
  44. public DataContractJsonSerializer (Type type)
  45. : this (type, Type.EmptyTypes)
  46. {
  47. }
  48. public DataContractJsonSerializer (Type type, IEnumerable<Type> knownTypes)
  49. : this (type, default_root_name, knownTypes)
  50. {
  51. }
  52. public DataContractJsonSerializer (Type type, string rootName)
  53. : this (type, rootName, Type.EmptyTypes)
  54. {
  55. }
  56. public DataContractJsonSerializer (Type type, XmlDictionaryString rootName)
  57. : this (type, rootName != null ? rootName.Value : default_root_name, Type.EmptyTypes)
  58. {
  59. }
  60. public DataContractJsonSerializer (Type type, string rootName, IEnumerable<Type> knownTypes)
  61. : this (type, rootName, knownTypes, int.MaxValue, false, false)
  62. {
  63. }
  64. public DataContractJsonSerializer (Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes)
  65. : this (type, rootName != null ? rootName.Value : default_root_name, knownTypes)
  66. {
  67. }
  68. DataContractJsonSerializer(Type type, string rootName, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool alwaysEmitTypeInformation)
  69. {
  70. if (type == null)
  71. throw new ArgumentNullException ("type");
  72. if (rootName == null)
  73. throw new ArgumentNullException ("rootName");
  74. if (maxItemsInObjectGraph < 0)
  75. throw new ArgumentOutOfRangeException ("maxItemsInObjectGraph");
  76. this.type = type;
  77. var knownTypesFromAttributes = new List<Type> ();
  78. foreach (var attr in type.GetCustomAttributes (typeof (KnownTypeAttribute), false))
  79. knownTypesFromAttributes.Add ((attr as KnownTypeAttribute).Type);
  80. if (knownTypes != null)
  81. knownTypesFromAttributes.AddRange (knownTypes);
  82. known_types = new ReadOnlyCollection<Type> (knownTypesFromAttributes);
  83. root = rootName;
  84. max_items = maxItemsInObjectGraph;
  85. ignore_extension = ignoreExtensionDataObject;
  86. always_emit_type = alwaysEmitTypeInformation;
  87. }
  88. public DataContractJsonSerializer (Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, bool alwaysEmitTypeInformation)
  89. : this (type, default_root_name, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, alwaysEmitTypeInformation)
  90. {
  91. }
  92. public DataContractJsonSerializer (Type type, string rootName, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, bool alwaysEmitTypeInformation)
  93. : this (type, rootName, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, alwaysEmitTypeInformation)
  94. {
  95. surrogate = dataContractSurrogate;
  96. }
  97. public DataContractJsonSerializer (Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, bool alwaysEmitTypeInformation)
  98. : this (type, rootName != null ? rootName.Value : default_root_name, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, alwaysEmitTypeInformation)
  99. {
  100. }
  101. public DataContractJsonSerializer (Type type, DataContractJsonSerializerSettings settings)
  102. : this (type, settings.RootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject,
  103. settings.DataContractSurrogate, false)
  104. {
  105. }
  106. #endregion
  107. Type type;
  108. string root;
  109. ReadOnlyCollection<Type> known_types;
  110. int max_items;
  111. bool ignore_extension;
  112. bool always_emit_type;
  113. IDataContractSurrogate surrogate;
  114. [MonoTODO]
  115. public IDataContractSurrogate DataContractSurrogate {
  116. get { return surrogate; }
  117. }
  118. [MonoTODO]
  119. public bool IgnoreExtensionDataObject {
  120. get { return ignore_extension; }
  121. }
  122. public ReadOnlyCollection<Type> KnownTypes {
  123. get { return known_types; }
  124. }
  125. public int MaxItemsInObjectGraph {
  126. get { return max_items; }
  127. }
  128. public override bool IsStartObject (XmlReader reader)
  129. {
  130. if (reader == null)
  131. throw new ArgumentNullException ("reader");
  132. reader.MoveToContent ();
  133. return reader.IsStartElement (root, String.Empty);
  134. }
  135. public override bool IsStartObject (XmlDictionaryReader reader)
  136. {
  137. return IsStartObject ((XmlReader) reader);
  138. }
  139. public override object ReadObject (Stream stream)
  140. {
  141. #if NET_2_1
  142. var r = (JsonReader) JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max);
  143. r.LameSilverlightLiteralParser = true;
  144. return ReadObject(r);
  145. #else
  146. return ReadObject (JsonReaderWriterFactory.CreateJsonReader (stream, new XmlDictionaryReaderQuotas ()));
  147. #endif
  148. }
  149. public override object ReadObject (XmlDictionaryReader reader)
  150. {
  151. return ReadObject (reader, true);
  152. }
  153. public override object ReadObject (XmlReader reader)
  154. {
  155. return ReadObject (reader, true);
  156. }
  157. public override object ReadObject (XmlDictionaryReader reader, bool verifyObjectName)
  158. {
  159. return ReadObject ((XmlReader) reader, verifyObjectName);
  160. }
  161. public override object ReadObject (XmlReader reader, bool verifyObjectName)
  162. {
  163. if (reader == null)
  164. throw new ArgumentNullException ("reader");
  165. try {
  166. if (verifyObjectName && !IsStartObject (reader))
  167. throw new SerializationException (String.Format ("Expected element was '{0}', but the actual input element was '{1}' in namespace '{2}'", root, reader.LocalName, reader.NamespaceURI));
  168. return new JsonSerializationReader (this, reader, type, verifyObjectName).ReadRoot ();
  169. } catch (SerializationException) {
  170. throw;
  171. } catch (InvalidDataContractException) {
  172. throw;
  173. } catch (System.Reflection.TargetInvocationException ex) {
  174. throw ex.InnerException;
  175. } catch (Exception ex) {
  176. throw new SerializationException ("Deserialization has failed", ex);
  177. }
  178. }
  179. public override void WriteObject (Stream stream, object graph)
  180. {
  181. using (var xw = JsonReaderWriterFactory.CreateJsonWriter (stream))
  182. WriteObject (xw, graph);
  183. }
  184. public override void WriteObject (XmlWriter writer, object graph)
  185. {
  186. try {
  187. WriteStartObject (writer, graph);
  188. WriteObjectContent (writer, graph);
  189. WriteEndObject (writer);
  190. } catch (NotImplementedException) {
  191. throw;
  192. } catch (InvalidDataContractException) {
  193. throw;
  194. } catch (Exception ex) {
  195. throw new SerializationException (String.Format ("There was an error during serialization for object of type {0}", graph != null ? graph.GetType () : null), ex);
  196. }
  197. }
  198. public override void WriteObject (XmlDictionaryWriter writer, object graph)
  199. {
  200. WriteObject ((XmlWriter) writer, graph);
  201. }
  202. public override void WriteStartObject (XmlDictionaryWriter writer, object graph)
  203. {
  204. WriteStartObject ((XmlWriter) writer, graph);
  205. }
  206. public override void WriteStartObject (XmlWriter writer, object graph)
  207. {
  208. if (writer == null)
  209. throw new ArgumentNullException ("writer");
  210. writer.WriteStartElement (root);
  211. }
  212. public override void WriteObjectContent (XmlDictionaryWriter writer, object graph)
  213. {
  214. WriteObjectContent ((XmlWriter) writer, graph);
  215. }
  216. public override void WriteObjectContent (XmlWriter writer, object graph)
  217. {
  218. new JsonSerializationWriter (this, writer, type, always_emit_type).WriteObjectContent (graph, true, false);
  219. }
  220. public override void WriteEndObject (XmlDictionaryWriter writer)
  221. {
  222. WriteEndObject ((XmlWriter) writer);
  223. }
  224. public override void WriteEndObject (XmlWriter writer)
  225. {
  226. if (writer == null)
  227. throw new ArgumentNullException ("writer");
  228. writer.WriteEndElement ();
  229. }
  230. [MonoTODO]
  231. public DateTimeFormat DateTimeFormat {
  232. get { throw new NotImplementedException (); }
  233. }
  234. [MonoTODO]
  235. public EmitTypeInformation EmitTypeInformation {
  236. get { throw new NotImplementedException (); }
  237. }
  238. [MonoTODO]
  239. public bool SerializeReadOnlyTypes {
  240. get { throw new NotImplementedException (); }
  241. }
  242. [MonoTODO]
  243. public bool UseSimpleDictionaryFormat {
  244. get { throw new NotImplementedException (); }
  245. }
  246. }
  247. }