JsonSerializationWriter.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. //
  2. // JsonSerializationWriter.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.Reflection;
  35. using System.Text;
  36. using System.Xml;
  37. namespace System.Runtime.Serialization.Json
  38. {
  39. class JsonSerializationWriter
  40. {
  41. DataContractJsonSerializer serializer;
  42. XmlWriter writer;
  43. int serialized_object_count;
  44. bool always_emit_type;
  45. Dictionary<Type, TypeMap> typemaps = new Dictionary<Type, TypeMap> ();
  46. Type root_type;
  47. public JsonSerializationWriter (DataContractJsonSerializer serializer, XmlWriter writer, Type rootType, bool alwaysEmitTypeInformation)
  48. {
  49. this.serializer = serializer;
  50. this.writer = writer;
  51. this.root_type = rootType;
  52. this.always_emit_type = alwaysEmitTypeInformation;
  53. }
  54. public XmlWriter Writer {
  55. get { return writer; }
  56. }
  57. public void WriteObjectContent (object graph, bool top, bool outputTypeName)
  58. {
  59. if (graph == null) {
  60. if (top)
  61. GetTypeMap (root_type); // to make sure to reject invalid contracts
  62. writer.WriteString (null);
  63. return;
  64. }
  65. if (serialized_object_count ++ == serializer.MaxItemsInObjectGraph)
  66. throw new SerializationException (String.Format ("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph));
  67. switch (Type.GetTypeCode (graph.GetType ())) {
  68. case TypeCode.Char:
  69. case TypeCode.String:
  70. writer.WriteString (graph.ToString ());
  71. break;
  72. case TypeCode.Single:
  73. case TypeCode.Double:
  74. writer.WriteAttributeString ("type", "number");
  75. writer.WriteString (((IFormattable) graph).ToString ("R", CultureInfo.InvariantCulture));
  76. break;
  77. case TypeCode.Byte:
  78. case TypeCode.SByte:
  79. case TypeCode.Int16:
  80. case TypeCode.Int32:
  81. case TypeCode.Int64:
  82. case TypeCode.UInt16:
  83. case TypeCode.UInt32:
  84. case TypeCode.UInt64:
  85. case TypeCode.Decimal:
  86. writer.WriteAttributeString ("type", "number");
  87. if (graph.GetType ().IsEnum)
  88. graph = ((IConvertible) graph).ToType (Enum.GetUnderlyingType (graph.GetType ()), CultureInfo.InvariantCulture);
  89. writer.WriteString (((IFormattable) graph).ToString ("G", CultureInfo.InvariantCulture));
  90. break;
  91. case TypeCode.Boolean:
  92. writer.WriteAttributeString ("type", "boolean");
  93. if ((bool) graph)
  94. writer.WriteString ("true");
  95. else
  96. writer.WriteString ("false");
  97. break;
  98. case TypeCode.DateTime:
  99. writer.WriteString (String.Format (CultureInfo.InvariantCulture, "/Date({0})/", (long) ((DateTime) graph).Subtract (new DateTime (1970, 1, 1)).TotalMilliseconds));
  100. break;
  101. default:
  102. if (graph is Guid) {
  103. goto case TypeCode.String;
  104. } else if (graph is Uri) {
  105. goto case TypeCode.String;
  106. } else if (graph is XmlQualifiedName) {
  107. XmlQualifiedName qn = (XmlQualifiedName) graph;
  108. writer.WriteString (qn.Name);
  109. writer.WriteString (":");
  110. writer.WriteString (qn.Namespace);
  111. } else if (TypeMap.IsDictionary (graph.GetType ())) {
  112. writer.WriteAttributeString ("type", "array");
  113. var itemGetter = graph.GetType ().GetProperty ("Item");
  114. var keysGetter = graph.GetType ().GetProperty ("Keys");
  115. var argarr = new object [1];
  116. foreach (object o in (IEnumerable) keysGetter.GetValue (graph, null)) {
  117. writer.WriteStartElement ("item");
  118. writer.WriteAttributeString ("type", "object");
  119. // outputting a KeyValuePair as <Key .. /><Value ... />
  120. writer.WriteStartElement ("Key");
  121. WriteObjectContent (o, false, !(graph is Array && graph.GetType ().GetElementType () != typeof (object)));
  122. writer.WriteEndElement ();
  123. writer.WriteStartElement ("Value");
  124. argarr [0] = o;
  125. WriteObjectContent (itemGetter.GetValue (graph, argarr), false, !(graph is Array && graph.GetType ().GetElementType () != typeof (object)));
  126. writer.WriteEndElement ();
  127. writer.WriteEndElement ();
  128. }
  129. } else if (TypeMap.IsCollection (graph.GetType ())) { // array
  130. writer.WriteAttributeString ("type", "array");
  131. foreach (object o in (ICollection) graph) {
  132. writer.WriteStartElement ("item");
  133. // when it is typed, then no need to output "__type"
  134. WriteObjectContent (o, false, !(graph is Array && graph.GetType ().GetElementType () != typeof (object)));
  135. writer.WriteEndElement ();
  136. }
  137. } else { // object
  138. TypeMap tm = GetTypeMap (graph.GetType ());
  139. if (tm != null) {
  140. // FIXME: I'm not sure how it is determined whether __type is written or not...
  141. if (outputTypeName || always_emit_type)
  142. writer.WriteAttributeString ("__type", FormatTypeName (graph.GetType ()));
  143. tm.Serialize (this, graph, "object");
  144. }
  145. else
  146. // it does not emit type="object" (as the graph is regarded as a string)
  147. // writer.WriteString (graph.ToString ());
  148. throw new InvalidDataContractException (String.Format ("Type {0} cannot be serialized by this JSON serializer", graph.GetType ()));
  149. }
  150. break;
  151. }
  152. }
  153. string FormatTypeName (Type type)
  154. {
  155. return String.Format ("{0}:#{1}", type.Name, type.Namespace);
  156. }
  157. TypeMap GetTypeMap (Type type)
  158. {
  159. TypeMap map;
  160. if (!typemaps.TryGetValue (type, out map)) {
  161. map = TypeMap.CreateTypeMap (type);
  162. typemaps [type] = map;
  163. }
  164. return map;
  165. }
  166. }
  167. }