2
0

JsonWriter.cs 15 KB

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