JSON.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. /*
  6. * Public Domain Niklas Frykholm
  7. */
  8. using System.Collections.Generic;
  9. using System.Collections;
  10. using System.Linq;
  11. using System.Text;
  12. using System;
  13. namespace Crown
  14. {
  15. /// <summary>
  16. /// Provides functions for encoding and decoding files in the JSON format.
  17. /// </summary>
  18. public class JSON
  19. {
  20. /// <summary>
  21. /// Encodes the hashtable t in the JSON format. The hash table can
  22. /// contain, numbers, bools, strings, ArrayLists and Hashtables.
  23. /// </summary>
  24. public static string Encode(object t)
  25. {
  26. StringBuilder builder = new StringBuilder();
  27. Write(t, builder, 0);
  28. builder.AppendLine();
  29. return builder.ToString();
  30. }
  31. /// <summary>
  32. /// Decodes a JSON bytestream into a hash table with numbers, bools, strings,
  33. /// ArrayLists and Hashtables.
  34. /// </summary>
  35. public static object Decode(byte[] sjson)
  36. {
  37. int index = 0;
  38. return Parse(sjson, ref index);
  39. }
  40. /// <summary>
  41. /// Convenience function for loading a file.
  42. /// </summary>
  43. public static Hashtable Load(string path)
  44. {
  45. System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
  46. byte[] bytes = new byte[fs.Length];
  47. fs.Read(bytes, 0, bytes.Length);
  48. fs.Close();
  49. return Decode(bytes) as Hashtable;
  50. }
  51. /// <summary>
  52. /// Convenience function for saving a file.
  53. /// </summary>
  54. public static void Save(Hashtable h, string path)
  55. {
  56. string s = Encode(h);
  57. System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.Create);
  58. byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s);
  59. fs.Write(bytes, 0, bytes.Count());
  60. fs.Close();
  61. }
  62. static void WriteNewLine(StringBuilder builder, int indentation)
  63. {
  64. builder.Append('\n');
  65. for (int i = 0; i < indentation; ++i)
  66. builder.Append('\t');
  67. }
  68. static void Write(object o, StringBuilder builder, int indentation)
  69. {
  70. if (o == null)
  71. builder.Append("null");
  72. else if (o is Boolean && (bool)o == false)
  73. builder.Append("false");
  74. else if (o is Boolean)
  75. builder.Append("true");
  76. else if (o is int)
  77. builder.Append((int)o);
  78. else if (o is float)
  79. builder.Append((float)o);
  80. else if (o is double)
  81. builder.Append((double)o);
  82. else if (o is string)
  83. WriteString((String)o, builder);
  84. else if (o is ArrayList)
  85. WriteArray((ArrayList)o, builder, indentation);
  86. else if (o is Hashtable)
  87. WriteObject((Hashtable)o, builder, indentation);
  88. else
  89. throw new ArgumentException("Unknown object");
  90. }
  91. static void WriteString(String s, StringBuilder builder)
  92. {
  93. builder.Append('"');
  94. for (int i = 0; i < s.Length; ++i)
  95. {
  96. Char c = s[i];
  97. if (c == '"' || c == '\\')
  98. {
  99. builder.Append('\\');
  100. builder.Append(c);
  101. }
  102. else if (c == '\n')
  103. {
  104. builder.Append('\\');
  105. builder.Append('n');
  106. }
  107. else
  108. builder.Append(c);
  109. }
  110. builder.Append('"');
  111. }
  112. static void WriteArray(ArrayList a, StringBuilder builder, int indentation)
  113. {
  114. bool write_comma = false;
  115. builder.Append("[ ");
  116. foreach (object item in a)
  117. {
  118. if (write_comma)
  119. builder.Append(", ");
  120. Write(item, builder, indentation + 1);
  121. write_comma = true;
  122. }
  123. builder.Append("]");
  124. }
  125. static void WriteObject(Hashtable t, StringBuilder builder, int indentation)
  126. {
  127. builder.Append('{');
  128. bool write_comma = false;
  129. foreach (DictionaryEntry de in t)
  130. {
  131. if (write_comma)
  132. builder.Append(", ");
  133. WriteNewLine(builder, indentation);
  134. Write(de.Key, builder, indentation);
  135. builder.Append(" : ");
  136. Write(de.Value, builder, indentation);
  137. write_comma = true;
  138. }
  139. WriteNewLine(builder, indentation);
  140. builder.Append('}');
  141. }
  142. static bool AtEnd(byte[] json, ref int index)
  143. {
  144. SkipWhitespace(json, ref index);
  145. return (index >= json.Length);
  146. }
  147. static void SkipWhitespace(byte[] json, ref int index)
  148. {
  149. while (index < json.Length)
  150. {
  151. byte c = json[index];
  152. if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',')
  153. ++index;
  154. else
  155. break;
  156. }
  157. }
  158. static void Consume(byte[] json, ref int index, String consume)
  159. {
  160. SkipWhitespace(json, ref index);
  161. for (int i = 0; i < consume.Length; ++i)
  162. {
  163. if (json[index] != consume[i])
  164. throw new FormatException();
  165. ++index;
  166. }
  167. }
  168. static object Parse(byte[] json, ref int index)
  169. {
  170. byte c = Next(json, ref index);
  171. if (c == '{')
  172. return ParseObject(json, ref index);
  173. else if (c == '[')
  174. return ParseArray(json, ref index);
  175. else if (c == '"')
  176. return ParseString(json, ref index);
  177. else if (c == '-' || c >= '0' && c <= '9')
  178. return ParseNumber(json, ref index);
  179. else if (c == 't')
  180. {
  181. Consume(json, ref index, "true");
  182. return true;
  183. }
  184. else if (c == 'f')
  185. {
  186. Consume(json, ref index, "false");
  187. return false;
  188. }
  189. else if (c == 'n')
  190. {
  191. Consume(json, ref index, "null");
  192. return null;
  193. }
  194. else
  195. throw new FormatException();
  196. }
  197. static byte Next(byte[] json, ref int index)
  198. {
  199. SkipWhitespace(json, ref index);
  200. return json[index];
  201. }
  202. static Hashtable ParseObject(byte[] json, ref int index)
  203. {
  204. Hashtable ht = new Hashtable();
  205. Consume(json, ref index, "{");
  206. SkipWhitespace(json, ref index);
  207. while (Next(json, ref index) != '}')
  208. {
  209. String key = ParseString(json, ref index);
  210. Consume(json, ref index, ":");
  211. if (key.EndsWith("_binary"))
  212. ht[key] = ParseBinary(json, ref index);
  213. else
  214. ht[key] = Parse(json, ref index);
  215. }
  216. Consume(json, ref index, "}");
  217. return ht;
  218. }
  219. static ArrayList ParseArray(byte[] json, ref int index)
  220. {
  221. ArrayList a = new ArrayList();
  222. Consume(json, ref index, "[");
  223. while (Next(json, ref index) != ']')
  224. {
  225. object value = Parse(json, ref index);
  226. a.Add(value);
  227. }
  228. Consume(json, ref index, "]");
  229. return a;
  230. }
  231. static byte[] ParseBinary(byte[] json, ref int index)
  232. {
  233. List<byte> s = new List<byte>();
  234. Consume(json, ref index, "\"");
  235. while (true)
  236. {
  237. byte c = json[index];
  238. ++index;
  239. if (c == '"')
  240. break;
  241. else if (c != '\\')
  242. s.Add(c);
  243. else
  244. {
  245. byte q = json[index];
  246. ++index;
  247. if (q == '"' || q == '\\' || q == '/')
  248. s.Add(q);
  249. else if (q == 'b') s.Add((byte)'\b');
  250. else if (q == 'f') s.Add((byte)'\f');
  251. else if (q == 'n') s.Add((byte)'\n');
  252. else if (q == 'r') s.Add((byte)'\r');
  253. else if (q == 't') s.Add((byte)'\t');
  254. else if (q == 'u')
  255. {
  256. throw new FormatException();
  257. }
  258. else
  259. {
  260. throw new FormatException();
  261. }
  262. }
  263. }
  264. return s.ToArray();
  265. }
  266. static String ParseString(byte[] json, ref int index)
  267. {
  268. return new UTF8Encoding().GetString(ParseBinary(json, ref index));
  269. }
  270. static Double ParseNumber(byte[] json, ref int index)
  271. {
  272. int end = index;
  273. while ("0123456789+-.eE".IndexOf((char)json[end]) != -1)
  274. ++end;
  275. byte[] num = new byte[end - index];
  276. Array.Copy(json, index, num, 0, num.Length);
  277. index = end;
  278. String numstr = new UTF8Encoding().GetString(num);
  279. return Double.Parse(numstr);
  280. }
  281. }
  282. }