SJSON.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. builder.Append(' ');
  133. Write(item, builder, indentation+1);
  134. }
  135. builder.Append(" ]");
  136. }
  137. static void WriteObject(Hashtable t, StringBuilder builder, int indentation)
  138. {
  139. builder.Append('{');
  140. WriteObjectFields(t, builder, indentation+1);
  141. WriteNewLine(builder, indentation);
  142. builder.Append('}');
  143. }
  144. static Hashtable ParseRootObject(byte [] json, ref int index)
  145. {
  146. Hashtable ht = new Hashtable();
  147. while (!AtEnd(json, ref index)) {
  148. String key = ParseIdentifier(json, ref index);
  149. Consume(json, ref index, "=");
  150. object value = ParseValue(json, ref index);
  151. ht[key] = value;
  152. }
  153. return ht;
  154. }
  155. static bool AtEnd(byte [] json, ref int index)
  156. {
  157. SkipWhitespace(json, ref index);
  158. return (index >= json.Length);
  159. }
  160. static void SkipWhitespace(byte [] json, ref int index)
  161. {
  162. while (index < json.Length) {
  163. byte c = json[index];
  164. if (c == '/')
  165. SkipComment(json, ref index);
  166. else if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',')
  167. ++index;
  168. else
  169. break;
  170. }
  171. }
  172. static void SkipComment(byte [] json, ref int index)
  173. {
  174. byte next = json[index + 1];
  175. if (next == '/')
  176. {
  177. while (index + 1 < json.Length && json[index] != '\n')
  178. ++index;
  179. ++index;
  180. }
  181. else if (next == '*')
  182. {
  183. while (index + 2 < json.Length && (json[index] != '*' || json[index + 1] != '/'))
  184. ++index;
  185. index += 2;
  186. }
  187. else
  188. throw new FormatException();
  189. }
  190. static String ParseIdentifier(byte [] json, ref int index)
  191. {
  192. SkipWhitespace(json, ref index);
  193. if (json[index] == '"')
  194. return ParseString(json, ref index);
  195. List<byte> s = new List<byte>();
  196. while (true) {
  197. byte c = json[index];
  198. if (c == ' ' || c == '\t' || c == '\n' || c == '=')
  199. break;
  200. s.Add(c);
  201. ++index;
  202. }
  203. return new UTF8Encoding().GetString(s.ToArray());
  204. }
  205. static void Consume(byte [] json, ref int index, String consume)
  206. {
  207. SkipWhitespace(json, ref index);
  208. for (int i=0; i<consume.Length; ++i) {
  209. if (json[index] != consume[i])
  210. throw new FormatException();
  211. ++index;
  212. }
  213. }
  214. static object ParseValue(byte [] json, ref int index)
  215. {
  216. byte c = Next(json, ref index);
  217. if (c == '{')
  218. return ParseObject(json, ref index);
  219. else if (c == '[')
  220. return ParseArray(json, ref index);
  221. else if (c == '"')
  222. return ParseString(json, ref index);
  223. else if (c == '-' || c >= '0' && c <= '9')
  224. return ParseNumber(json, ref index);
  225. else if (c == 't')
  226. {
  227. Consume(json, ref index, "true");
  228. return true;
  229. }
  230. else if (c == 'f')
  231. {
  232. Consume(json, ref index, "false");
  233. return false;
  234. }
  235. else if (c == 'n')
  236. {
  237. Consume(json, ref index, "null");
  238. return null;
  239. }
  240. else
  241. throw new FormatException();
  242. }
  243. static byte Next(byte [] json, ref int index)
  244. {
  245. SkipWhitespace(json, ref index);
  246. return json[index];
  247. }
  248. static Hashtable ParseObject(byte [] json, ref int index)
  249. {
  250. Hashtable ht = new Hashtable();
  251. Consume(json, ref index, "{");
  252. SkipWhitespace(json, ref index);
  253. while (Next(json, ref index) != '}') {
  254. String key = ParseIdentifier(json, ref index);
  255. Consume(json, ref index, "=");
  256. object value = ParseValue(json, ref index);
  257. ht[key] = value;
  258. }
  259. Consume(json, ref index, "}");
  260. return ht;
  261. }
  262. static ArrayList ParseArray(byte [] json, ref int index)
  263. {
  264. ArrayList a = new ArrayList();
  265. Consume(json, ref index, "[");
  266. while (Next(json, ref index) != ']') {
  267. object value = ParseValue(json, ref index);
  268. a.Add(value);
  269. }
  270. Consume(json, ref index, "]");
  271. return a;
  272. }
  273. static String ParseString(byte[] json, ref int index)
  274. {
  275. List<byte> s = new List<byte>();
  276. Consume(json, ref index, "\"");
  277. while (true) {
  278. byte c = json[index];
  279. ++index;
  280. if (c == '"')
  281. break;
  282. else if (c != '\\')
  283. s.Add(c);
  284. else {
  285. byte q = json[index];
  286. ++index;
  287. if (q == '"' || q == '\\' || q == '/')
  288. s.Add(q);
  289. else if (q == 'b') s.Add((byte)'\b');
  290. else if (q == 'f') s.Add((byte)'\f');
  291. else if (q == 'n') s.Add((byte)'\n');
  292. else if (q == 'r') s.Add((byte)'\r');
  293. else if (q == 't') s.Add((byte)'\t');
  294. else if (q == 'u') {
  295. throw new FormatException();
  296. } else {
  297. throw new FormatException();
  298. }
  299. }
  300. }
  301. return new UTF8Encoding().GetString(s.ToArray());
  302. }
  303. static Double ParseNumber(byte[] json, ref int index)
  304. {
  305. int end = index;
  306. while (end < json.Length && "0123456789+-.eE".IndexOf((char)json[end]) != -1)
  307. ++end;
  308. byte[] num = new byte[end - index];
  309. Array.Copy(json, index, num, 0, num.Length);
  310. index = end;
  311. String numstr = new UTF8Encoding().GetString(num);
  312. return Double.Parse(numstr);
  313. }
  314. }
  315. }