JsonWriter.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. 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. writer.Write(str[i]);
  221. }
  222. writer.Write ('"');
  223. }
  224. private void Unindent ()
  225. {
  226. if (pretty_print)
  227. indentation -= indent_value;
  228. }
  229. #endregion
  230. public override string ToString ()
  231. {
  232. if (inst_string_builder == null)
  233. return String.Empty;
  234. return inst_string_builder.ToString ();
  235. }
  236. public void Reset ()
  237. {
  238. has_reached_end = false;
  239. ctx_stack.Clear ();
  240. context = new WriterContext ();
  241. ctx_stack.Push (context);
  242. if (inst_string_builder != null)
  243. inst_string_builder.Remove (0, inst_string_builder.Length);
  244. }
  245. public void Write (bool boolean)
  246. {
  247. DoValidation (Condition.Value);
  248. PutNewline ();
  249. Put (boolean ? "true" : "false");
  250. context.ExpectingValue = false;
  251. }
  252. public void Write (decimal number)
  253. {
  254. DoValidation (Condition.Value);
  255. PutNewline ();
  256. Put (Convert.ToString (number, number_format));
  257. context.ExpectingValue = false;
  258. }
  259. public void Write (double number)
  260. {
  261. DoValidation (Condition.Value);
  262. PutNewline ();
  263. string str = Convert.ToString (number, number_format);
  264. Put (str);
  265. if (str.IndexOf ('.') == -1 &&
  266. str.IndexOf ('E') == -1)
  267. writer.Write (".0");
  268. context.ExpectingValue = false;
  269. }
  270. public void Write(float number)
  271. {
  272. DoValidation(Condition.Value);
  273. PutNewline();
  274. string str = Convert.ToString(number, number_format);
  275. Put(str);
  276. context.ExpectingValue = false;
  277. }
  278. public void Write (int number)
  279. {
  280. DoValidation (Condition.Value);
  281. PutNewline ();
  282. Put (Convert.ToString (number, number_format));
  283. context.ExpectingValue = false;
  284. }
  285. public void Write (long number)
  286. {
  287. DoValidation (Condition.Value);
  288. PutNewline ();
  289. Put (Convert.ToString (number, number_format));
  290. context.ExpectingValue = false;
  291. }
  292. public void WriteJsonWrapper(IJsonWrapper json)
  293. {
  294. if (context.InArray)
  295. {
  296. DoValidation(Condition.Value);
  297. PutNewline();
  298. this.TextWriter.Write(json.ToJson());
  299. context.ExpectingValue = false;
  300. }
  301. else
  302. {
  303. this.TextWriter.Write(json.ToJson());
  304. }
  305. }
  306. public void Write (string str)
  307. {
  308. DoValidation (Condition.Value);
  309. PutNewline ();
  310. if (str == null)
  311. Put ("null");
  312. else
  313. PutString (str);
  314. context.ExpectingValue = false;
  315. }
  316. //[CLSCompliant(false)]
  317. public void Write (ulong number)
  318. {
  319. DoValidation (Condition.Value);
  320. PutNewline ();
  321. Put (Convert.ToString (number, number_format));
  322. context.ExpectingValue = false;
  323. }
  324. public void WriteArrayEnd ()
  325. {
  326. DoValidation (Condition.InArray);
  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 WriteArrayStart ()
  339. {
  340. DoValidation (Condition.NotAProperty);
  341. PutNewline ();
  342. Put ("[");
  343. context = new WriterContext ();
  344. context.InArray = true;
  345. ctx_stack.Push (context);
  346. Indent ();
  347. }
  348. public void WriteObjectEnd ()
  349. {
  350. DoValidation (Condition.InObject);
  351. PutNewline (false);
  352. ctx_stack.Pop ();
  353. if (ctx_stack.Count == 1)
  354. has_reached_end = true;
  355. else {
  356. context = ctx_stack.Peek ();
  357. context.ExpectingValue = false;
  358. }
  359. Unindent ();
  360. Put ("}");
  361. }
  362. public void WriteObjectStart ()
  363. {
  364. DoValidation (Condition.NotAProperty);
  365. PutNewline ();
  366. Put ("{");
  367. context = new WriterContext ();
  368. context.InObject = true;
  369. ctx_stack.Push (context);
  370. Indent ();
  371. }
  372. public void WritePropertyName (string property_name)
  373. {
  374. DoValidation (Condition.Property);
  375. PutNewline ();
  376. string propertyName = (property_name == null || !lower_case_properties)
  377. ? property_name
  378. : property_name.ToLowerInvariant();
  379. PutString (propertyName);
  380. if (pretty_print) {
  381. if (propertyName.Length > context.Padding)
  382. context.Padding = propertyName.Length;
  383. for (int i = context.Padding - propertyName.Length;
  384. i >= 0; i--)
  385. writer.Write (' ');
  386. writer.Write (": ");
  387. } else
  388. writer.Write (':');
  389. context.ExpectingValue = true;
  390. }
  391. }
  392. }