JsonWriter.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 = false;
  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. writer.Write(str);
  189. writer.Write('"');
  190. return;
  191. /*
  192. int n = str.Length;
  193. for (int i = 0; i < n; i++) {
  194. switch (str[i]) {
  195. case '\n':
  196. writer.Write ("\\n");
  197. continue;
  198. case '\r':
  199. writer.Write ("\\r");
  200. continue;
  201. case '\t':
  202. writer.Write ("\\t");
  203. continue;
  204. case '"':
  205. case '\\':
  206. writer.Write ('\\');
  207. writer.Write (str[i]);
  208. continue;
  209. case '\f':
  210. writer.Write ("\\f");
  211. continue;
  212. case '\b':
  213. writer.Write ("\\b");
  214. continue;
  215. }
  216. if ((int) str[i] >= 32 && (int) str[i] <= 126) {
  217. writer.Write (str[i]);
  218. continue;
  219. }
  220. // Default, turn into a \uXXXX sequence
  221. IntToHex ((int) str[i], hex_seq);
  222. writer.Write ("\\u");
  223. writer.Write (hex_seq);
  224. }
  225. writer.Write ('"');
  226. */
  227. }
  228. private void Unindent ()
  229. {
  230. if (pretty_print)
  231. indentation -= indent_value;
  232. }
  233. #endregion
  234. public override string ToString ()
  235. {
  236. if (inst_string_builder == null)
  237. return String.Empty;
  238. return inst_string_builder.ToString ();
  239. }
  240. public void Reset ()
  241. {
  242. has_reached_end = false;
  243. ctx_stack.Clear ();
  244. context = new WriterContext ();
  245. ctx_stack.Push (context);
  246. if (inst_string_builder != null)
  247. inst_string_builder.Remove (0, inst_string_builder.Length);
  248. }
  249. public void Write (bool boolean)
  250. {
  251. DoValidation (Condition.Value);
  252. PutNewline ();
  253. Put (boolean ? "true" : "false");
  254. context.ExpectingValue = false;
  255. }
  256. public void Write (decimal number)
  257. {
  258. DoValidation (Condition.Value);
  259. PutNewline ();
  260. Put (Convert.ToString (number, number_format));
  261. context.ExpectingValue = false;
  262. }
  263. public void Write (double number)
  264. {
  265. DoValidation (Condition.Value);
  266. PutNewline ();
  267. string str = Convert.ToString (number, number_format);
  268. Put (str);
  269. if (str.IndexOf ('.') == -1 &&
  270. str.IndexOf ('E') == -1)
  271. writer.Write (".0");
  272. context.ExpectingValue = false;
  273. }
  274. public void Write(float number)
  275. {
  276. DoValidation(Condition.Value);
  277. PutNewline();
  278. string str = Convert.ToString(number, number_format);
  279. Put(str);
  280. context.ExpectingValue = false;
  281. }
  282. public void Write (int number)
  283. {
  284. DoValidation (Condition.Value);
  285. PutNewline ();
  286. Put (Convert.ToString (number, number_format));
  287. context.ExpectingValue = false;
  288. }
  289. public void Write (long number)
  290. {
  291. DoValidation (Condition.Value);
  292. PutNewline ();
  293. Put (Convert.ToString (number, number_format));
  294. context.ExpectingValue = false;
  295. }
  296. public void Write (string str)
  297. {
  298. DoValidation (Condition.Value);
  299. PutNewline ();
  300. if (str == null)
  301. Put ("null");
  302. else
  303. PutString (str);
  304. context.ExpectingValue = false;
  305. }
  306. public void Write (ulong number)
  307. {
  308. DoValidation (Condition.Value);
  309. PutNewline ();
  310. Put (Convert.ToString (number, number_format));
  311. context.ExpectingValue = false;
  312. }
  313. public void WriteArrayEnd ()
  314. {
  315. DoValidation (Condition.InArray);
  316. PutNewline (false);
  317. ctx_stack.Pop ();
  318. if (ctx_stack.Count == 1)
  319. has_reached_end = true;
  320. else {
  321. context = ctx_stack.Peek ();
  322. context.ExpectingValue = false;
  323. }
  324. Unindent ();
  325. Put ("]");
  326. }
  327. public void WriteArrayStart ()
  328. {
  329. DoValidation (Condition.NotAProperty);
  330. PutNewline ();
  331. Put ("[");
  332. context = new WriterContext ();
  333. context.InArray = true;
  334. ctx_stack.Push (context);
  335. Indent ();
  336. }
  337. public void WriteObjectEnd ()
  338. {
  339. DoValidation (Condition.InObject);
  340. PutNewline (false);
  341. ctx_stack.Pop ();
  342. if (ctx_stack.Count == 1)
  343. has_reached_end = true;
  344. else {
  345. context = ctx_stack.Peek ();
  346. context.ExpectingValue = false;
  347. }
  348. Unindent ();
  349. Put ("}");
  350. }
  351. public void WriteObjectStart ()
  352. {
  353. DoValidation (Condition.NotAProperty);
  354. PutNewline ();
  355. Put ("{");
  356. context = new WriterContext ();
  357. context.InObject = true;
  358. ctx_stack.Push (context);
  359. Indent ();
  360. }
  361. public void WritePropertyName (string property_name)
  362. {
  363. DoValidation (Condition.Property);
  364. PutNewline ();
  365. string propertyName = (property_name == null || !lower_case_properties)
  366. ? property_name
  367. : property_name.ToLowerInvariant();
  368. PutString (propertyName);
  369. if (pretty_print) {
  370. if (propertyName.Length > context.Padding)
  371. context.Padding = propertyName.Length;
  372. for (int i = context.Padding - propertyName.Length;
  373. i >= 0; i--)
  374. writer.Write (' ');
  375. writer.Write (": ");
  376. } else
  377. writer.Write (':');
  378. context.ExpectingValue = true;
  379. }
  380. }
  381. }