JsonWriter.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. #region Header
  2. /**
  3. * JsonWriter.cs
  4. * Stream-like facility to output JSON text.
  5. *
  6. * The authors disclaim copyright to this source code. For more details, see
  7. * the COPYING file included with this distribution.
  8. **/
  9. #endregion
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Text;
  15. namespace LitJson
  16. {
  17. internal enum Condition
  18. {
  19. InArray,
  20. InObject,
  21. NotAProperty,
  22. Property,
  23. Value
  24. }
  25. internal class WriterContext
  26. {
  27. public int Count;
  28. public bool InArray;
  29. public bool InObject;
  30. public bool ExpectingValue;
  31. public int Padding;
  32. }
  33. public class JsonWriter
  34. {
  35. #region Fields
  36. private static readonly NumberFormatInfo number_format;
  37. private WriterContext context;
  38. private Stack<WriterContext> ctx_stack;
  39. private bool has_reached_end;
  40. private char[] hex_seq;
  41. private int indentation;
  42. private int indent_value;
  43. private StringBuilder inst_string_builder;
  44. private bool pretty_print;
  45. private bool validate;
  46. private bool lower_case_properties;
  47. private TextWriter writer;
  48. #endregion
  49. #region Properties
  50. public int IndentValue {
  51. get { return indent_value; }
  52. set {
  53. indentation = (indentation / indent_value) * value;
  54. indent_value = value;
  55. }
  56. }
  57. public bool PrettyPrint {
  58. get { return pretty_print; }
  59. set { pretty_print = value; }
  60. }
  61. public TextWriter TextWriter {
  62. get { return writer; }
  63. }
  64. public bool Validate {
  65. get { return validate; }
  66. set { validate = value; }
  67. }
  68. public bool LowerCaseProperties {
  69. get { return lower_case_properties; }
  70. set { lower_case_properties = value; }
  71. }
  72. #endregion
  73. #region Constructors
  74. static JsonWriter ()
  75. {
  76. number_format = NumberFormatInfo.InvariantInfo;
  77. }
  78. public JsonWriter ()
  79. {
  80. inst_string_builder = new StringBuilder ();
  81. writer = new StringWriter (inst_string_builder);
  82. Init ();
  83. }
  84. public JsonWriter (StringBuilder sb) :
  85. this (new StringWriter (sb))
  86. {
  87. }
  88. public JsonWriter (TextWriter writer)
  89. {
  90. if (writer == null)
  91. throw new ArgumentNullException ("writer");
  92. this.writer = writer;
  93. Init ();
  94. }
  95. #endregion
  96. #region Private Methods
  97. private void DoValidation (Condition cond)
  98. {
  99. if (! context.ExpectingValue)
  100. context.Count++;
  101. if (! validate)
  102. return;
  103. if (has_reached_end)
  104. throw new JsonException (
  105. "A complete JSON symbol has already been written");
  106. switch (cond) {
  107. case Condition.InArray:
  108. if (! context.InArray)
  109. throw new JsonException (
  110. "Can't close an array here");
  111. break;
  112. case Condition.InObject:
  113. if (! context.InObject || context.ExpectingValue)
  114. throw new JsonException (
  115. "Can't close an object here");
  116. break;
  117. case Condition.NotAProperty:
  118. if (context.InObject && ! context.ExpectingValue)
  119. throw new JsonException (
  120. "Expected a property");
  121. break;
  122. case Condition.Property:
  123. if (! context.InObject || context.ExpectingValue)
  124. throw new JsonException (
  125. "Can't add a property here");
  126. break;
  127. case Condition.Value:
  128. if (! context.InArray &&
  129. (! context.InObject || ! context.ExpectingValue))
  130. throw new JsonException (
  131. "Can't add a value here");
  132. break;
  133. }
  134. }
  135. private void Init ()
  136. {
  137. has_reached_end = false;
  138. hex_seq = new char[4];
  139. indentation = 0;
  140. indent_value = 4;
  141. pretty_print = true;
  142. validate = true;
  143. lower_case_properties = false;
  144. ctx_stack = new Stack<WriterContext> ();
  145. context = new WriterContext ();
  146. ctx_stack.Push (context);
  147. }
  148. private static void IntToHex (int n, char[] hex)
  149. {
  150. int num;
  151. for (int i = 0; i < 4; i++) {
  152. num = n % 16;
  153. if (num < 10)
  154. hex[3 - i] = (char) ('0' + num);
  155. else
  156. hex[3 - i] = (char) ('A' + (num - 10));
  157. n >>= 4;
  158. }
  159. }
  160. private void Indent ()
  161. {
  162. if (pretty_print)
  163. indentation += indent_value;
  164. }
  165. private void Put (string str)
  166. {
  167. if (pretty_print && ! context.ExpectingValue)
  168. for (int i = 0; i < indentation; i++)
  169. writer.Write (' ');
  170. writer.Write (str);
  171. }
  172. private void PutNewline ()
  173. {
  174. PutNewline (true);
  175. }
  176. private void PutNewline (bool add_comma)
  177. {
  178. if (add_comma && ! context.ExpectingValue &&
  179. context.Count > 1)
  180. writer.Write (',');
  181. if (pretty_print && ! context.ExpectingValue)
  182. writer.Write (Environment.NewLine);
  183. }
  184. private void PutString (string str)
  185. {
  186. Put (String.Empty);
  187. writer.Write ('"');
  188. int n = str.Length;
  189. for (int i = 0; i < n; i++) {
  190. switch (str[i]) {
  191. case '\n':
  192. writer.Write ("\\n");
  193. continue;
  194. case '\r':
  195. writer.Write ("\\r");
  196. continue;
  197. case '\t':
  198. writer.Write ("\\t");
  199. continue;
  200. case '"':
  201. case '\\':
  202. writer.Write ('\\');
  203. writer.Write (str[i]);
  204. continue;
  205. case '\f':
  206. writer.Write ("\\f");
  207. continue;
  208. case '\b':
  209. writer.Write ("\\b");
  210. continue;
  211. }
  212. if ((int) str[i] >= 32 && (int) str[i] <= 126) {
  213. writer.Write (str[i]);
  214. continue;
  215. }
  216. // Default, turn into a \uXXXX sequence
  217. IntToHex ((int) str[i], hex_seq);
  218. writer.Write ("\\u");
  219. writer.Write (hex_seq);
  220. }
  221. writer.Write ('"');
  222. }
  223. private void Unindent ()
  224. {
  225. if (pretty_print)
  226. indentation -= indent_value;
  227. }
  228. #endregion
  229. public override string ToString ()
  230. {
  231. if (inst_string_builder == null)
  232. return String.Empty;
  233. return inst_string_builder.ToString ();
  234. }
  235. public void Reset ()
  236. {
  237. has_reached_end = false;
  238. ctx_stack.Clear ();
  239. context = new WriterContext ();
  240. ctx_stack.Push (context);
  241. if (inst_string_builder != null)
  242. inst_string_builder.Remove (0, inst_string_builder.Length);
  243. }
  244. public void Write (bool boolean)
  245. {
  246. DoValidation (Condition.Value);
  247. PutNewline ();
  248. Put (boolean ? "true" : "false");
  249. context.ExpectingValue = false;
  250. }
  251. public void Write (decimal number)
  252. {
  253. DoValidation (Condition.Value);
  254. PutNewline ();
  255. Put (Convert.ToString (number, number_format));
  256. context.ExpectingValue = false;
  257. }
  258. public void Write (double number)
  259. {
  260. DoValidation (Condition.Value);
  261. PutNewline ();
  262. string str = Convert.ToString (number, number_format);
  263. Put (str);
  264. if (str.IndexOf ('.') == -1 &&
  265. str.IndexOf ('E') == -1)
  266. writer.Write (".0");
  267. context.ExpectingValue = false;
  268. }
  269. public void Write(float number)
  270. {
  271. DoValidation(Condition.Value);
  272. PutNewline();
  273. string str = Convert.ToString(number, number_format);
  274. Put(str);
  275. context.ExpectingValue = false;
  276. }
  277. public void Write (int number)
  278. {
  279. DoValidation (Condition.Value);
  280. PutNewline ();
  281. Put (Convert.ToString (number, number_format));
  282. context.ExpectingValue = false;
  283. }
  284. public void Write (long number)
  285. {
  286. DoValidation (Condition.Value);
  287. PutNewline ();
  288. Put (Convert.ToString (number, number_format));
  289. context.ExpectingValue = false;
  290. }
  291. public void Write (string str)
  292. {
  293. DoValidation (Condition.Value);
  294. PutNewline ();
  295. if (str == null)
  296. Put ("null");
  297. else
  298. PutString (str);
  299. context.ExpectingValue = false;
  300. }
  301. [CLSCompliant(false)]
  302. public void Write (ulong number)
  303. {
  304. DoValidation (Condition.Value);
  305. PutNewline ();
  306. Put (Convert.ToString (number, number_format));
  307. context.ExpectingValue = false;
  308. }
  309. public void WriteArrayEnd ()
  310. {
  311. DoValidation (Condition.InArray);
  312. PutNewline (false);
  313. ctx_stack.Pop ();
  314. if (ctx_stack.Count == 1)
  315. has_reached_end = true;
  316. else {
  317. context = ctx_stack.Peek ();
  318. context.ExpectingValue = false;
  319. }
  320. Unindent ();
  321. Put ("]");
  322. }
  323. public void WriteArrayStart ()
  324. {
  325. DoValidation (Condition.NotAProperty);
  326. PutNewline ();
  327. Put ("[");
  328. context = new WriterContext ();
  329. context.InArray = true;
  330. ctx_stack.Push (context);
  331. Indent ();
  332. }
  333. public void WriteObjectEnd ()
  334. {
  335. DoValidation (Condition.InObject);
  336. PutNewline (false);
  337. ctx_stack.Pop ();
  338. if (ctx_stack.Count == 1)
  339. has_reached_end = true;
  340. else {
  341. context = ctx_stack.Peek ();
  342. context.ExpectingValue = false;
  343. }
  344. Unindent ();
  345. Put ("}");
  346. }
  347. public void WriteObjectStart ()
  348. {
  349. DoValidation (Condition.NotAProperty);
  350. PutNewline ();
  351. Put ("{");
  352. context = new WriterContext ();
  353. context.InObject = true;
  354. ctx_stack.Push (context);
  355. Indent ();
  356. }
  357. public void WritePropertyName (string property_name)
  358. {
  359. DoValidation (Condition.Property);
  360. PutNewline ();
  361. string propertyName = (property_name == null || !lower_case_properties)
  362. ? property_name
  363. : property_name.ToLowerInvariant();
  364. PutString (propertyName);
  365. if (pretty_print) {
  366. if (propertyName.Length > context.Padding)
  367. context.Padding = propertyName.Length;
  368. for (int i = context.Padding - propertyName.Length;
  369. i >= 0; i--)
  370. writer.Write (' ');
  371. writer.Write (": ");
  372. } else
  373. writer.Write (':');
  374. context.ExpectingValue = true;
  375. }
  376. }
  377. }