JsonWriter.cs 11 KB

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