JsonWriter.cs 13 KB

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