JsonWriter.cs 15 KB

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