JsonWriter.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 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 TextWriter writer;
  47. #endregion
  48. #region Properties
  49. public int IndentValue {
  50. get { return indent_value; }
  51. set {
  52. indentation = (indentation / indent_value) * value;
  53. indent_value = value;
  54. }
  55. }
  56. public bool PrettyPrint {
  57. get { return pretty_print; }
  58. set { pretty_print = value; }
  59. }
  60. public TextWriter TextWriter {
  61. get { return writer; }
  62. }
  63. public bool Validate {
  64. get { return validate; }
  65. set { validate = value; }
  66. }
  67. #endregion
  68. #region Constructors
  69. static JsonWriter ()
  70. {
  71. number_format = NumberFormatInfo.InvariantInfo;
  72. }
  73. public JsonWriter ()
  74. {
  75. inst_string_builder = new StringBuilder ();
  76. writer = new StringWriter (inst_string_builder);
  77. Init ();
  78. }
  79. public JsonWriter (StringBuilder sb) :
  80. this (new StringWriter (sb))
  81. {
  82. }
  83. public JsonWriter (TextWriter writer)
  84. {
  85. if (writer == null)
  86. throw new ArgumentNullException ("writer");
  87. this.writer = writer;
  88. Init ();
  89. }
  90. #endregion
  91. #region Private Methods
  92. private void DoValidation (Condition cond)
  93. {
  94. if (! context.ExpectingValue)
  95. context.Count++;
  96. if (! validate)
  97. return;
  98. if (has_reached_end)
  99. throw new JsonException (
  100. "A complete JSON symbol has already been written");
  101. switch (cond) {
  102. case Condition.InArray:
  103. if (! context.InArray)
  104. throw new JsonException (
  105. "Can't close an array here");
  106. break;
  107. case Condition.InObject:
  108. if (! context.InObject || context.ExpectingValue)
  109. throw new JsonException (
  110. "Can't close an object here");
  111. break;
  112. case Condition.NotAProperty:
  113. if (context.InObject && ! context.ExpectingValue)
  114. throw new JsonException (
  115. "Expected a property");
  116. break;
  117. case Condition.Property:
  118. if (! context.InObject || context.ExpectingValue)
  119. throw new JsonException (
  120. "Can't add a property here");
  121. break;
  122. case Condition.Value:
  123. if (! context.InArray &&
  124. (! context.InObject || ! context.ExpectingValue))
  125. throw new JsonException (
  126. "Can't add a value here");
  127. break;
  128. }
  129. }
  130. private void Init ()
  131. {
  132. has_reached_end = false;
  133. hex_seq = new char[4];
  134. indentation = 0;
  135. indent_value = 4;
  136. pretty_print = false;
  137. validate = true;
  138. ctx_stack = new Stack<WriterContext> ();
  139. context = new WriterContext ();
  140. ctx_stack.Push (context);
  141. }
  142. private static void IntToHex (int n, char[] hex)
  143. {
  144. int num;
  145. for (int i = 0; i < 4; i++) {
  146. num = n % 16;
  147. if (num < 10)
  148. hex[3 - i] = (char) ('0' + num);
  149. else
  150. hex[3 - i] = (char) ('A' + (num - 10));
  151. n >>= 4;
  152. }
  153. }
  154. private void Indent ()
  155. {
  156. if (pretty_print)
  157. indentation += indent_value;
  158. }
  159. private void Put (string str)
  160. {
  161. if (pretty_print && ! context.ExpectingValue)
  162. for (int i = 0; i < indentation; i++)
  163. writer.Write (' ');
  164. writer.Write (str);
  165. }
  166. private void PutNewline ()
  167. {
  168. PutNewline (true);
  169. }
  170. private void PutNewline (bool add_comma)
  171. {
  172. if (add_comma && ! context.ExpectingValue &&
  173. context.Count > 1)
  174. writer.Write (',');
  175. if (pretty_print && ! context.ExpectingValue)
  176. writer.Write ('\n');
  177. }
  178. private void PutString (string str)
  179. {
  180. Put (String.Empty);
  181. writer.Write ('"');
  182. //直接存储原始字符串,不再做任何转义字符的解析
  183. writer.Write(str);
  184. writer.Write('"');
  185. return;
  186. /*
  187. int n = str.Length;
  188. for (int i = 0; i < n; i++) {
  189. switch (str[i]) {
  190. case '\n':
  191. writer.Write ("\\n");
  192. continue;
  193. case '\r':
  194. writer.Write ("\\r");
  195. continue;
  196. case '\t':
  197. writer.Write ("\\t");
  198. continue;
  199. case '"':
  200. case '\\':
  201. writer.Write ('\\');
  202. writer.Write (str[i]);
  203. continue;
  204. case '\f':
  205. writer.Write ("\\f");
  206. continue;
  207. case '\b':
  208. writer.Write ("\\b");
  209. continue;
  210. }
  211. if ((int) str[i] >= 32 && (int) str[i] <= 126) {
  212. writer.Write (str[i]);
  213. continue;
  214. }
  215. // Default, turn into a \uXXXX sequence
  216. IntToHex ((int) str[i], hex_seq);
  217. writer.Write ("\\u");
  218. writer.Write (hex_seq);
  219. }
  220. writer.Write ('"');
  221. */
  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 (int number)
  270. {
  271. DoValidation (Condition.Value);
  272. PutNewline ();
  273. Put (Convert.ToString (number, number_format));
  274. context.ExpectingValue = false;
  275. }
  276. public void Write (long number)
  277. {
  278. DoValidation (Condition.Value);
  279. PutNewline ();
  280. Put (Convert.ToString (number, number_format));
  281. context.ExpectingValue = false;
  282. }
  283. public void Write (string str)
  284. {
  285. DoValidation (Condition.Value);
  286. PutNewline ();
  287. if (str == null)
  288. Put ("null");
  289. else
  290. PutString (str);
  291. context.ExpectingValue = false;
  292. }
  293. public void Write (ulong number)
  294. {
  295. DoValidation (Condition.Value);
  296. PutNewline ();
  297. Put (Convert.ToString (number, number_format));
  298. context.ExpectingValue = false;
  299. }
  300. public void WriteArrayEnd ()
  301. {
  302. DoValidation (Condition.InArray);
  303. PutNewline (false);
  304. ctx_stack.Pop ();
  305. if (ctx_stack.Count == 1)
  306. has_reached_end = true;
  307. else {
  308. context = ctx_stack.Peek ();
  309. context.ExpectingValue = false;
  310. }
  311. Unindent ();
  312. Put ("]");
  313. }
  314. public void WriteArrayStart ()
  315. {
  316. DoValidation (Condition.NotAProperty);
  317. PutNewline ();
  318. Put ("[");
  319. context = new WriterContext ();
  320. context.InArray = true;
  321. ctx_stack.Push (context);
  322. Indent ();
  323. }
  324. public void WriteObjectEnd ()
  325. {
  326. DoValidation (Condition.InObject);
  327. PutNewline (false);
  328. ctx_stack.Pop ();
  329. if (ctx_stack.Count == 1)
  330. has_reached_end = true;
  331. else {
  332. context = ctx_stack.Peek ();
  333. context.ExpectingValue = false;
  334. }
  335. Unindent ();
  336. Put ("}");
  337. }
  338. public void WriteObjectStart ()
  339. {
  340. DoValidation (Condition.NotAProperty);
  341. PutNewline ();
  342. Put ("{");
  343. context = new WriterContext ();
  344. context.InObject = true;
  345. ctx_stack.Push (context);
  346. Indent ();
  347. }
  348. public void WritePropertyName (string property_name)
  349. {
  350. DoValidation (Condition.Property);
  351. PutNewline ();
  352. PutString (property_name);
  353. if (pretty_print) {
  354. if (property_name.Length > context.Padding)
  355. context.Padding = property_name.Length;
  356. for (int i = context.Padding - property_name.Length;
  357. i >= 0; i--)
  358. writer.Write (' ');
  359. writer.Write (": ");
  360. } else
  361. writer.Write (':');
  362. context.ExpectingValue = true;
  363. }
  364. public void Write(float number)
  365. {
  366. DoValidation(Condition.Value);
  367. PutNewline();
  368. string str = number.ToString();
  369. Put(str);
  370. context.ExpectingValue = false;
  371. }
  372. }
  373. }