Json.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. using System;
  30. using System.IO;
  31. using System.Text;
  32. using System.Collections;
  33. using System.Globalization;
  34. using System.Collections.Generic;
  35. namespace Spine {
  36. public static class Json {
  37. public static object Deserialize (TextReader text) {
  38. var parser = new SharpJson.JsonDecoder();
  39. parser.parseNumbersAsFloat = true;
  40. return parser.Decode(text.ReadToEnd());
  41. }
  42. }
  43. }
  44. /**
  45. * Copyright (c) 2016 Adriano Tinoco d'Oliveira Rezende
  46. *
  47. * Based on the JSON parser by Patrick van Bergen
  48. * http://techblog.procurios.nl/k/news/view/14605/14863/how-do-i-write-my-own-parser-(for-json).html
  49. *
  50. * Changes made:
  51. *
  52. * - Optimized parser speed (deserialize roughly near 3x faster than original)
  53. * - Added support to handle lexer/parser error messages with line numbers
  54. * - Added more fine grained control over type conversions during the parsing
  55. * - Refactory API (Separate Lexer code from Parser code and the Encoder from Decoder)
  56. *
  57. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
  58. * and associated documentation files (the "Software"), to deal in the Software without restriction,
  59. * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  60. * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
  61. * subject to the following conditions:
  62. * The above copyright notice and this permission notice shall be included in all copies or substantial
  63. * portions of the Software.
  64. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
  65. * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  66. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  67. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  68. * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  69. */
  70. namespace SharpJson
  71. {
  72. class Lexer
  73. {
  74. public enum Token {
  75. None,
  76. Null,
  77. True,
  78. False,
  79. Colon,
  80. Comma,
  81. String,
  82. Number,
  83. CurlyOpen,
  84. CurlyClose,
  85. SquaredOpen,
  86. SquaredClose,
  87. };
  88. public bool hasError {
  89. get {
  90. return !success;
  91. }
  92. }
  93. public int lineNumber {
  94. get;
  95. private set;
  96. }
  97. public bool parseNumbersAsFloat {
  98. get;
  99. set;
  100. }
  101. char[] json;
  102. int index = 0;
  103. bool success = true;
  104. char[] stringBuffer = new char[4096];
  105. public Lexer(string text)
  106. {
  107. Reset();
  108. json = text.ToCharArray();
  109. parseNumbersAsFloat = false;
  110. }
  111. public void Reset()
  112. {
  113. index = 0;
  114. lineNumber = 1;
  115. success = true;
  116. }
  117. public string ParseString()
  118. {
  119. int idx = 0;
  120. StringBuilder builder = null;
  121. SkipWhiteSpaces();
  122. // "
  123. char c = json[index++];
  124. bool failed = false;
  125. bool complete = false;
  126. while (!complete && !failed) {
  127. if (index == json.Length)
  128. break;
  129. c = json[index++];
  130. if (c == '"') {
  131. complete = true;
  132. break;
  133. } else if (c == '\\') {
  134. if (index == json.Length)
  135. break;
  136. c = json[index++];
  137. switch (c) {
  138. case '"':
  139. stringBuffer[idx++] = '"';
  140. break;
  141. case '\\':
  142. stringBuffer[idx++] = '\\';
  143. break;
  144. case '/':
  145. stringBuffer[idx++] = '/';
  146. break;
  147. case 'b':
  148. stringBuffer[idx++] = '\b';
  149. break;
  150. case'f':
  151. stringBuffer[idx++] = '\f';
  152. break;
  153. case 'n':
  154. stringBuffer[idx++] = '\n';
  155. break;
  156. case 'r':
  157. stringBuffer[idx++] = '\r';
  158. break;
  159. case 't':
  160. stringBuffer[idx++] = '\t';
  161. break;
  162. case 'u':
  163. int remainingLength = json.Length - index;
  164. if (remainingLength >= 4) {
  165. var hex = new string(json, index, 4);
  166. // XXX: handle UTF
  167. stringBuffer[idx++] = (char) Convert.ToInt32(hex, 16);
  168. // skip 4 chars
  169. index += 4;
  170. } else {
  171. failed = true;
  172. }
  173. break;
  174. }
  175. } else {
  176. stringBuffer[idx++] = c;
  177. }
  178. if (idx >= stringBuffer.Length) {
  179. if (builder == null)
  180. builder = new StringBuilder();
  181. builder.Append(stringBuffer, 0, idx);
  182. idx = 0;
  183. }
  184. }
  185. if (!complete) {
  186. success = false;
  187. return null;
  188. }
  189. if (builder != null)
  190. return builder.ToString ();
  191. else
  192. return new string (stringBuffer, 0, idx);
  193. }
  194. string GetNumberString()
  195. {
  196. SkipWhiteSpaces();
  197. int lastIndex = GetLastIndexOfNumber(index);
  198. int charLength = (lastIndex - index) + 1;
  199. var result = new string (json, index, charLength);
  200. index = lastIndex + 1;
  201. return result;
  202. }
  203. public float ParseFloatNumber()
  204. {
  205. float number;
  206. var str = GetNumberString ();
  207. if (!float.TryParse (str, NumberStyles.Float, CultureInfo.InvariantCulture, out number))
  208. return 0;
  209. return number;
  210. }
  211. public double ParseDoubleNumber()
  212. {
  213. double number;
  214. var str = GetNumberString ();
  215. if (!double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out number))
  216. return 0;
  217. return number;
  218. }
  219. int GetLastIndexOfNumber(int index)
  220. {
  221. int lastIndex;
  222. for (lastIndex = index; lastIndex < json.Length; lastIndex++) {
  223. char ch = json[lastIndex];
  224. if ((ch < '0' || ch > '9') && ch != '+' && ch != '-'
  225. && ch != '.' && ch != 'e' && ch != 'E')
  226. break;
  227. }
  228. return lastIndex - 1;
  229. }
  230. void SkipWhiteSpaces()
  231. {
  232. for (; index < json.Length; index++) {
  233. char ch = json[index];
  234. if (ch == '\n')
  235. lineNumber++;
  236. if (!char.IsWhiteSpace(json[index]))
  237. break;
  238. }
  239. }
  240. public Token LookAhead()
  241. {
  242. SkipWhiteSpaces();
  243. int savedIndex = index;
  244. return NextToken(json, ref savedIndex);
  245. }
  246. public Token NextToken()
  247. {
  248. SkipWhiteSpaces();
  249. return NextToken(json, ref index);
  250. }
  251. static Token NextToken(char[] json, ref int index)
  252. {
  253. if (index == json.Length)
  254. return Token.None;
  255. char c = json[index++];
  256. switch (c) {
  257. case '{':
  258. return Token.CurlyOpen;
  259. case '}':
  260. return Token.CurlyClose;
  261. case '[':
  262. return Token.SquaredOpen;
  263. case ']':
  264. return Token.SquaredClose;
  265. case ',':
  266. return Token.Comma;
  267. case '"':
  268. return Token.String;
  269. case '0': case '1': case '2': case '3': case '4':
  270. case '5': case '6': case '7': case '8': case '9':
  271. case '-':
  272. return Token.Number;
  273. case ':':
  274. return Token.Colon;
  275. }
  276. index--;
  277. int remainingLength = json.Length - index;
  278. // false
  279. if (remainingLength >= 5) {
  280. if (json[index] == 'f' &&
  281. json[index + 1] == 'a' &&
  282. json[index + 2] == 'l' &&
  283. json[index + 3] == 's' &&
  284. json[index + 4] == 'e') {
  285. index += 5;
  286. return Token.False;
  287. }
  288. }
  289. // true
  290. if (remainingLength >= 4) {
  291. if (json[index] == 't' &&
  292. json[index + 1] == 'r' &&
  293. json[index + 2] == 'u' &&
  294. json[index + 3] == 'e') {
  295. index += 4;
  296. return Token.True;
  297. }
  298. }
  299. // null
  300. if (remainingLength >= 4) {
  301. if (json[index] == 'n' &&
  302. json[index + 1] == 'u' &&
  303. json[index + 2] == 'l' &&
  304. json[index + 3] == 'l') {
  305. index += 4;
  306. return Token.Null;
  307. }
  308. }
  309. return Token.None;
  310. }
  311. }
  312. public class JsonDecoder
  313. {
  314. public string errorMessage {
  315. get;
  316. private set;
  317. }
  318. public bool parseNumbersAsFloat {
  319. get;
  320. set;
  321. }
  322. Lexer lexer;
  323. public JsonDecoder()
  324. {
  325. errorMessage = null;
  326. parseNumbersAsFloat = false;
  327. }
  328. public object Decode(string text)
  329. {
  330. errorMessage = null;
  331. lexer = new Lexer(text);
  332. lexer.parseNumbersAsFloat = parseNumbersAsFloat;
  333. return ParseValue();
  334. }
  335. public static object DecodeText(string text)
  336. {
  337. var builder = new JsonDecoder();
  338. return builder.Decode(text);
  339. }
  340. IDictionary<string, object> ParseObject()
  341. {
  342. var table = new Dictionary<string, object>();
  343. // {
  344. lexer.NextToken();
  345. while (true) {
  346. var token = lexer.LookAhead();
  347. switch (token) {
  348. case Lexer.Token.None:
  349. TriggerError("Invalid token");
  350. return null;
  351. case Lexer.Token.Comma:
  352. lexer.NextToken();
  353. break;
  354. case Lexer.Token.CurlyClose:
  355. lexer.NextToken();
  356. return table;
  357. default:
  358. // name
  359. string name = EvalLexer(lexer.ParseString());
  360. if (errorMessage != null)
  361. return null;
  362. // :
  363. token = lexer.NextToken();
  364. if (token != Lexer.Token.Colon) {
  365. TriggerError("Invalid token; expected ':'");
  366. return null;
  367. }
  368. // value
  369. object value = ParseValue();
  370. if (errorMessage != null)
  371. return null;
  372. table[name] = value;
  373. break;
  374. }
  375. }
  376. //return null; // Unreachable code
  377. }
  378. IList<object> ParseArray()
  379. {
  380. var array = new List<object>();
  381. // [
  382. lexer.NextToken();
  383. while (true) {
  384. var token = lexer.LookAhead();
  385. switch (token) {
  386. case Lexer.Token.None:
  387. TriggerError("Invalid token");
  388. return null;
  389. case Lexer.Token.Comma:
  390. lexer.NextToken();
  391. break;
  392. case Lexer.Token.SquaredClose:
  393. lexer.NextToken();
  394. return array;
  395. default:
  396. object value = ParseValue();
  397. if (errorMessage != null)
  398. return null;
  399. array.Add(value);
  400. break;
  401. }
  402. }
  403. //return null; // Unreachable code
  404. }
  405. object ParseValue()
  406. {
  407. switch (lexer.LookAhead()) {
  408. case Lexer.Token.String:
  409. return EvalLexer(lexer.ParseString());
  410. case Lexer.Token.Number:
  411. if (parseNumbersAsFloat)
  412. return EvalLexer(lexer.ParseFloatNumber());
  413. else
  414. return EvalLexer(lexer.ParseDoubleNumber());
  415. case Lexer.Token.CurlyOpen:
  416. return ParseObject();
  417. case Lexer.Token.SquaredOpen:
  418. return ParseArray();
  419. case Lexer.Token.True:
  420. lexer.NextToken();
  421. return true;
  422. case Lexer.Token.False:
  423. lexer.NextToken();
  424. return false;
  425. case Lexer.Token.Null:
  426. lexer.NextToken();
  427. return null;
  428. case Lexer.Token.None:
  429. break;
  430. }
  431. TriggerError("Unable to parse value");
  432. return null;
  433. }
  434. void TriggerError(string message)
  435. {
  436. errorMessage = string.Format("Error: '{0}' at line {1}",
  437. message, lexer.lineNumber);
  438. }
  439. T EvalLexer<T>(T value)
  440. {
  441. if (lexer.hasError)
  442. TriggerError("Lexical error ocurred");
  443. return value;
  444. }
  445. }
  446. }