JsonWriter.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //
  2. // JsonWriter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2007 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.Generic;
  30. using System.Globalization;
  31. using System.IO;
  32. using System.Text;
  33. using System.Xml;
  34. namespace System.Runtime.Serialization.Json
  35. {
  36. class JsonWriter : XmlDictionaryWriter, IXmlJsonWriterInitializer
  37. {
  38. enum ElementType
  39. {
  40. None,
  41. Object,
  42. Array,
  43. String,
  44. Number,
  45. Boolean,
  46. }
  47. StreamWriter output;
  48. bool close_output;
  49. WriteState state;
  50. Stack<ElementType> element_kinds = new Stack<ElementType> ();
  51. Stack<bool> first_content_flags = new Stack<bool> ();
  52. string attr_name, attr_value, runtime_type;
  53. public JsonWriter (Stream stream, Encoding encoding, bool closeOutput)
  54. {
  55. SetOutput (stream, encoding, closeOutput);
  56. }
  57. public void SetOutput (Stream stream, Encoding encoding, bool ownsStream)
  58. {
  59. // null stream and encoding will be rejected by StreamWriter.ctor.
  60. output = new StreamWriter (stream, encoding);
  61. }
  62. void CheckState ()
  63. {
  64. switch (state) {
  65. case WriteState.Closed:
  66. case WriteState.Error:
  67. throw new InvalidOperationException (String.Format ("This XmlDictionaryReader is already at '{0}' state", state));
  68. }
  69. }
  70. // copied from System.Silverlight JavaScriptSerializer.
  71. static string EscapeStringLiteral (string input)
  72. {
  73. StringBuilder sb = null;
  74. int i = 0, start = 0;
  75. for (; i < input.Length; i++) {
  76. switch (input [i]) {
  77. case '"':
  78. AppendBuffer (ref sb, input, start, i, @"\""");
  79. break;
  80. case '\\':
  81. AppendBuffer (ref sb, input, start, i, @"\\");
  82. break;
  83. //case '/':
  84. // AppendBuffer (ref sb, input, start, i, @"\/");
  85. // break;
  86. case '\x8':
  87. AppendBuffer (ref sb, input, start, i, @"\b");
  88. break;
  89. case '\f':
  90. AppendBuffer (ref sb, input, start, i, @"\f");
  91. break;
  92. case '\n':
  93. AppendBuffer (ref sb, input, start, i, /*@"\n"*/@"\u000a");
  94. break;
  95. case '\r':
  96. AppendBuffer (ref sb, input, start, i, /*@"\r"*/@"\u000d");
  97. break;
  98. case '\t':
  99. AppendBuffer (ref sb, input, start, i, /*@"\t"*/@"\u0009");
  100. break;
  101. default:
  102. continue;
  103. }
  104. start = i + 1;
  105. }
  106. string remaining = input.Substring (start, i - start);
  107. if (sb != null)
  108. return sb.Append (remaining).ToString ();
  109. else
  110. return remaining;
  111. }
  112. static void AppendBuffer (ref StringBuilder sb, string input, int start, int i, string append)
  113. {
  114. if (sb == null)
  115. sb = new StringBuilder ();
  116. if (i != start)
  117. sb.Append (input, start, i - start);
  118. sb.Append (append);
  119. }
  120. public override WriteState WriteState {
  121. get { return state; }
  122. }
  123. public override void Close ()
  124. {
  125. // close all open elements
  126. while (element_kinds.Count > 0)
  127. WriteEndElement ();
  128. if (close_output)
  129. output.Close ();
  130. else
  131. output.Flush ();
  132. state = WriteState.Closed;
  133. }
  134. public override void Flush ()
  135. {
  136. output.Flush ();
  137. }
  138. public override void WriteStartElement (string prefix, string localName, string ns)
  139. {
  140. CheckState ();
  141. if (localName == null)
  142. throw new ArgumentNullException ("localName");
  143. else if (localName.Length == 0)
  144. throw new ArgumentException ("Empty string is not a valid localName in this XmlDictionaryWriter");
  145. if (!String.IsNullOrEmpty (ns))
  146. throw new ArgumentException ("Non-empty namespace URI is not allowed in this XmlDictionaryWriter");
  147. if (!String.IsNullOrEmpty (prefix))
  148. throw new ArgumentException ("Non-empty prefix is not allowed in this XmlDictionaryWriter");
  149. if (state == WriteState.Attribute)
  150. WriteEndAttribute ();
  151. if (state == WriteState.Element)
  152. CloseStartElement ();
  153. else if (state != WriteState.Start && element_kinds.Count == 0)
  154. throw new XmlException ("This XmlDictionaryWriter does not support multiple top-level elements");
  155. if (element_kinds.Count == 0) {
  156. if (localName != "root")
  157. throw new XmlException ("Only 'root' is allowed for the name of the top-level element");
  158. } else {
  159. switch (element_kinds.Peek ()) {
  160. case ElementType.Array:
  161. if (localName != "item")
  162. throw new XmlException ("Only 'item' is allowed as a content element of an array");
  163. break;
  164. case ElementType.String:
  165. throw new XmlException ("Mixed content is not allowed in this XmlDictionaryWriter");
  166. case ElementType.None:
  167. throw new XmlException ("Before writing a child element, an element needs 'type' attribute to indicate whether the element is a JSON array or a JSON object in this XmlDictionaryWriter");
  168. }
  169. if (first_content_flags.Peek ()) {
  170. first_content_flags.Pop ();
  171. first_content_flags.Push (false);
  172. }
  173. else
  174. output.Write (',');
  175. if (element_kinds.Peek () != ElementType.Array) {
  176. output.Write ('"');
  177. output.Write (localName);
  178. output.Write ("\":");
  179. }
  180. }
  181. element_kinds.Push (ElementType.None); // undetermined yet
  182. state = WriteState.Element;
  183. }
  184. public override void WriteEndElement ()
  185. {
  186. CheckState ();
  187. if (state == WriteState.Attribute)
  188. throw new XmlException ("Cannot end element when an attribute is being written");
  189. if (state == WriteState.Element)
  190. CloseStartElement ();
  191. if (element_kinds.Count == 0)
  192. throw new XmlException ("There is no open element to close");
  193. switch (element_kinds.Pop ()) {
  194. case ElementType.String:
  195. output.Write ('"');
  196. break;
  197. case ElementType.Array:
  198. output.Write (']');
  199. break;
  200. case ElementType.Object:
  201. output.Write ('}');
  202. break;
  203. }
  204. // not sure if it is correct though ...
  205. state = WriteState.Content;
  206. first_content_flags.Pop ();
  207. }
  208. public override void WriteFullEndElement ()
  209. {
  210. WriteEndElement (); // no such difference in JSON.
  211. }
  212. public override void WriteStartAttribute (string prefix, string localName, string ns)
  213. {
  214. CheckState ();
  215. if (state != WriteState.Element)
  216. throw new XmlException ("Cannot write attribute as this XmlDictionaryWriter is not at element state");
  217. if (!String.IsNullOrEmpty (ns))
  218. throw new ArgumentException ("Non-empty namespace URI is not allowed in this XmlDictionaryWriter");
  219. if (!String.IsNullOrEmpty (prefix))
  220. throw new ArgumentException ("Non-empty prefix is not allowed in this XmlDictionaryWriter");
  221. if (localName != "type" && localName != "__type")
  222. throw new ArgumentException ("Only 'type' and '__type' are allowed as an attribute name in this XmlDictionaryWriter");
  223. if (state != WriteState.Element)
  224. throw new InvalidOperationException (String.Format ("Attribute cannot be written in {0} mode", state));
  225. attr_name = localName;
  226. state = WriteState.Attribute;
  227. }
  228. public override void WriteEndAttribute ()
  229. {
  230. CheckState ();
  231. if (state != WriteState.Attribute)
  232. throw new XmlException ("Cannot close attribute, as this XmlDictionaryWriter is not at attribute state");
  233. if (attr_name == "type") {
  234. switch (attr_value) {
  235. case "object":
  236. element_kinds.Pop ();
  237. element_kinds.Push (ElementType.Object);
  238. output.Write ('{');
  239. break;
  240. case "array":
  241. element_kinds.Pop ();
  242. element_kinds.Push (ElementType.Array);
  243. output.Write ('[');
  244. break;
  245. case "number":
  246. element_kinds.Pop ();
  247. element_kinds.Push (ElementType.Number);
  248. break;
  249. case "boolean":
  250. element_kinds.Pop ();
  251. element_kinds.Push (ElementType.Boolean);
  252. break;
  253. case "string":
  254. element_kinds.Pop ();
  255. element_kinds.Push (ElementType.String);
  256. break;
  257. default:
  258. throw new XmlException (String.Format ("Unexpected type attribute value '{0}'", attr_value));
  259. }
  260. }
  261. else
  262. runtime_type = attr_value;
  263. state = WriteState.Element;
  264. attr_value = null;
  265. }
  266. void CloseStartElement ()
  267. {
  268. if (element_kinds.Peek () == ElementType.None) {
  269. element_kinds.Pop ();
  270. element_kinds.Push (ElementType.String);
  271. }
  272. if (element_kinds.Peek () == ElementType.String)
  273. output.Write ('"');
  274. first_content_flags.Push (true);
  275. if (runtime_type != null) {
  276. output.Write ("\"__type\":\"");
  277. output.Write (runtime_type);
  278. output.Write ('\"');
  279. runtime_type = null;
  280. first_content_flags.Pop ();
  281. first_content_flags.Push (false);
  282. }
  283. }
  284. public override void WriteString (string text)
  285. {
  286. CheckState ();
  287. if (state == WriteState.Start)
  288. throw new InvalidOperationException ("Top-level content string is not allowed in this XmlDictionaryWriter");
  289. if (state == WriteState.Element) {
  290. CloseStartElement ();
  291. state = WriteState.Content;
  292. }
  293. if (state == WriteState.Attribute)
  294. attr_value += text;
  295. else {
  296. switch (element_kinds.Peek ()) {
  297. case ElementType.String:
  298. case ElementType.Number:
  299. case ElementType.Boolean:
  300. break;
  301. default:
  302. throw new XmlException (String.Format ("Simple content string is allowed only for string, number and boolean types and not for {0} type", element_kinds.Peek ()));
  303. }
  304. output.Write (EscapeStringLiteral (text));
  305. }
  306. }
  307. #region mostly-ignored operations
  308. public override string LookupPrefix (string ns)
  309. {
  310. // Since there is no way to declare namespaces in
  311. // this writer, it always returns fixed results.
  312. if (ns == null)
  313. throw new ArgumentNullException ("ns");
  314. else if (ns.Length == 0)
  315. return String.Empty;
  316. else if (ns == "http://www.w3.org/2000/xmlns/")
  317. return "xmlns";
  318. else if (ns == "http://www.w3.org/XML/1998/namespace")
  319. return "xml";
  320. return null;
  321. }
  322. public override void WriteStartDocument ()
  323. {
  324. CheckState ();
  325. }
  326. public override void WriteStartDocument (bool standalone)
  327. {
  328. CheckState ();
  329. }
  330. public override void WriteEndDocument ()
  331. {
  332. CheckState ();
  333. }
  334. #endregion
  335. #region unsupported operations
  336. public override void WriteDocType (string name, string pubid, string sysid, string intSubset)
  337. {
  338. CheckState ();
  339. throw new NotSupportedException ("This XmlDictionaryWriter does not support writing doctype declaration");
  340. }
  341. public override void WriteComment (string text)
  342. {
  343. CheckState ();
  344. throw new NotSupportedException ("This XmlDictionaryWriter does not support writing comment");
  345. }
  346. public override void WriteEntityRef (string text)
  347. {
  348. CheckState ();
  349. throw new NotSupportedException ("This XmlDictionaryWriter does not support writing entity reference");
  350. }
  351. public override void WriteProcessingInstruction (string target, string data)
  352. {
  353. CheckState ();
  354. if (String.Compare (target, "xml", StringComparison.OrdinalIgnoreCase) != 0)
  355. throw new ArgumentException ("This XmlDictionaryWriter does not support writing processing instruction");
  356. }
  357. #endregion
  358. #region WriteString() variants
  359. public override void WriteRaw (string text)
  360. {
  361. WriteString (text);
  362. }
  363. public override void WriteRaw (char [] chars, int start, int length)
  364. {
  365. WriteChars (chars, start, length);
  366. }
  367. public override void WriteCData (string text)
  368. {
  369. WriteString (text);
  370. }
  371. public override void WriteCharEntity (char entity)
  372. {
  373. WriteString (entity.ToString ());
  374. }
  375. public override void WriteChars (char [] chars, int start, int length)
  376. {
  377. WriteString (new string (chars, start, length));
  378. }
  379. public override void WriteSurrogateCharEntity (char high, char low)
  380. {
  381. WriteChars (new char [] {high, low}, 0, 2);
  382. }
  383. public override void WriteBase64 (byte [] bytes, int start, int length)
  384. {
  385. WriteString (Convert.ToBase64String (bytes, start, length));
  386. }
  387. public override void WriteWhitespace (string text)
  388. {
  389. if (text == null)
  390. throw new ArgumentNullException ("text");
  391. for (int i = 0; i < text.Length; i++) {
  392. if (text [i] != ' ') {
  393. for (int j = i; j < text.Length; j++) {
  394. switch (text [j]) {
  395. case '\t':
  396. case ' ':
  397. case '\n':
  398. case '\r':
  399. continue;
  400. default:
  401. throw new ArgumentException (String.Format ("WriteWhitespace() does not accept non-whitespace character '{0}'", text [j]));
  402. }
  403. }
  404. break;
  405. }
  406. }
  407. WriteString (text);
  408. }
  409. #endregion
  410. }
  411. }