JsonWriter.cs 14 KB

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