JSON.cs 7.1 KB

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