JSON.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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;
  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. Write(item, builder, indentation + 1);
  120. write_comma = true;
  121. }
  122. builder.Append("]");
  123. }
  124. static void WriteObject(Hashtable t, StringBuilder builder, int indentation)
  125. {
  126. builder.Append('{');
  127. bool write_comma = false;
  128. foreach (DictionaryEntry de in t)
  129. {
  130. if (write_comma)
  131. builder.Append(", ");
  132. WriteNewLine(builder, indentation);
  133. Write(de.Key, builder, indentation);
  134. builder.Append(" : ");
  135. Write(de.Value, builder, indentation);
  136. write_comma = true;
  137. }
  138. WriteNewLine(builder, indentation);
  139. builder.Append('}');
  140. }
  141. static bool AtEnd(byte[] json, ref int index)
  142. {
  143. SkipWhitespace(json, ref index);
  144. return (index >= json.Length);
  145. }
  146. static void SkipWhitespace(byte[] json, ref int index)
  147. {
  148. while (index < json.Length)
  149. {
  150. byte c = json[index];
  151. if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',')
  152. ++index;
  153. else
  154. break;
  155. }
  156. }
  157. static void Consume(byte[] json, ref int index, String consume)
  158. {
  159. SkipWhitespace(json, ref index);
  160. for (int i = 0; i < consume.Length; ++i)
  161. {
  162. if (json[index] != consume[i])
  163. throw new FormatException();
  164. ++index;
  165. }
  166. }
  167. static object Parse(byte[] json, ref int index)
  168. {
  169. byte c = Next(json, ref index);
  170. if (c == '{')
  171. return ParseObject(json, ref index);
  172. else if (c == '[')
  173. return ParseArray(json, ref index);
  174. else if (c == '"')
  175. return ParseString(json, ref index);
  176. else if (c == '-' || c >= '0' && c <= '9')
  177. return ParseNumber(json, ref index);
  178. else if (c == 't')
  179. {
  180. Consume(json, ref index, "true");
  181. return true;
  182. }
  183. else if (c == 'f')
  184. {
  185. Consume(json, ref index, "false");
  186. return false;
  187. }
  188. else if (c == 'n')
  189. {
  190. Consume(json, ref index, "null");
  191. return null;
  192. }
  193. else
  194. throw new FormatException();
  195. }
  196. static byte Next(byte[] json, ref int index)
  197. {
  198. SkipWhitespace(json, ref index);
  199. return json[index];
  200. }
  201. static Hashtable ParseObject(byte[] json, ref int index)
  202. {
  203. Hashtable ht = new Hashtable();
  204. Consume(json, ref index, "{");
  205. SkipWhitespace(json, ref index);
  206. while (Next(json, ref index) != '}')
  207. {
  208. String key = ParseString(json, ref index);
  209. Consume(json, ref index, ":");
  210. if (key.EndsWith("_binary"))
  211. ht[key] = ParseBinary(json, ref index);
  212. else
  213. ht[key] = Parse(json, ref index);
  214. }
  215. Consume(json, ref index, "}");
  216. return ht;
  217. }
  218. static ArrayList ParseArray(byte[] json, ref int index)
  219. {
  220. ArrayList a = new ArrayList();
  221. Consume(json, ref index, "[");
  222. while (Next(json, ref index) != ']')
  223. {
  224. object value = Parse(json, ref index);
  225. a.Add(value);
  226. }
  227. Consume(json, ref index, "]");
  228. return a;
  229. }
  230. static byte[] ParseBinary(byte[] json, ref int index)
  231. {
  232. List<byte> s = new List<byte>();
  233. Consume(json, ref index, "\"");
  234. while (true)
  235. {
  236. byte c = json[index];
  237. ++index;
  238. if (c == '"')
  239. break;
  240. else if (c != '\\')
  241. s.Add(c);
  242. else
  243. {
  244. byte q = json[index];
  245. ++index;
  246. if (q == '"' || q == '\\' || q == '/')
  247. s.Add(q);
  248. else if (q == 'b') s.Add((byte)'\b');
  249. else if (q == 'f') s.Add((byte)'\f');
  250. else if (q == 'n') s.Add((byte)'\n');
  251. else if (q == 'r') s.Add((byte)'\r');
  252. else if (q == 't') s.Add((byte)'\t');
  253. else if (q == 'u')
  254. {
  255. throw new FormatException();
  256. }
  257. else
  258. {
  259. throw new FormatException();
  260. }
  261. }
  262. }
  263. return s.ToArray();
  264. }
  265. static String ParseString(byte[] json, ref int index)
  266. {
  267. return new UTF8Encoding().GetString(ParseBinary(json, ref index));
  268. }
  269. static Double ParseNumber(byte[] json, ref int index)
  270. {
  271. int end = index;
  272. while ("0123456789+-.eE".IndexOf((char)json[end]) != -1)
  273. ++end;
  274. byte[] num = new byte[end - index];
  275. Array.Copy(json, index, num, 0, num.Length);
  276. index = end;
  277. String numstr = new UTF8Encoding().GetString(num);
  278. return Double.Parse(numstr);
  279. }
  280. }
  281. }