SJSON.cs 8.5 KB

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