Json.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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.Collections;
  31. using System.Collections.Generic;
  32. using System.Globalization;
  33. using System.IO;
  34. using System.Text;
  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. class Lexer {
  72. public enum Token {
  73. None,
  74. Null,
  75. True,
  76. False,
  77. Colon,
  78. Comma,
  79. String,
  80. Number,
  81. CurlyOpen,
  82. CurlyClose,
  83. SquaredOpen,
  84. SquaredClose,
  85. };
  86. public bool hasError {
  87. get {
  88. return !success;
  89. }
  90. }
  91. public int lineNumber {
  92. get;
  93. private set;
  94. }
  95. public bool parseNumbersAsFloat {
  96. get;
  97. set;
  98. }
  99. char[] json;
  100. int index = 0;
  101. bool success = true;
  102. char[] stringBuffer = new char[4096];
  103. public Lexer (string text) {
  104. Reset();
  105. json = text.ToCharArray();
  106. parseNumbersAsFloat = false;
  107. }
  108. public void Reset () {
  109. index = 0;
  110. lineNumber = 1;
  111. success = true;
  112. }
  113. public string ParseString () {
  114. int idx = 0;
  115. StringBuilder builder = null;
  116. SkipWhiteSpaces();
  117. // "
  118. char c = json[index++];
  119. bool failed = false;
  120. bool complete = false;
  121. while (!complete && !failed) {
  122. if (index == json.Length)
  123. break;
  124. c = json[index++];
  125. if (c == '"') {
  126. complete = true;
  127. break;
  128. } else if (c == '\\') {
  129. if (index == json.Length)
  130. break;
  131. c = json[index++];
  132. switch (c) {
  133. case '"':
  134. stringBuffer[idx++] = '"';
  135. break;
  136. case '\\':
  137. stringBuffer[idx++] = '\\';
  138. break;
  139. case '/':
  140. stringBuffer[idx++] = '/';
  141. break;
  142. case 'b':
  143. stringBuffer[idx++] = '\b';
  144. break;
  145. case 'f':
  146. stringBuffer[idx++] = '\f';
  147. break;
  148. case 'n':
  149. stringBuffer[idx++] = '\n';
  150. break;
  151. case 'r':
  152. stringBuffer[idx++] = '\r';
  153. break;
  154. case 't':
  155. stringBuffer[idx++] = '\t';
  156. break;
  157. case 'u':
  158. int remainingLength = json.Length - index;
  159. if (remainingLength >= 4) {
  160. var hex = new string(json, index, 4);
  161. // XXX: handle UTF
  162. stringBuffer[idx++] = (char)Convert.ToInt32(hex, 16);
  163. // skip 4 chars
  164. index += 4;
  165. } else {
  166. failed = true;
  167. }
  168. break;
  169. }
  170. } else {
  171. stringBuffer[idx++] = c;
  172. }
  173. if (idx >= stringBuffer.Length) {
  174. if (builder == null)
  175. builder = new StringBuilder();
  176. builder.Append(stringBuffer, 0, idx);
  177. idx = 0;
  178. }
  179. }
  180. if (!complete) {
  181. success = false;
  182. return null;
  183. }
  184. if (builder != null)
  185. return builder.ToString();
  186. else
  187. return new string(stringBuffer, 0, idx);
  188. }
  189. string GetNumberString () {
  190. SkipWhiteSpaces();
  191. int lastIndex = GetLastIndexOfNumber(index);
  192. int charLength = (lastIndex - index) + 1;
  193. var result = new string(json, index, charLength);
  194. index = lastIndex + 1;
  195. return result;
  196. }
  197. public float ParseFloatNumber () {
  198. float number;
  199. var str = GetNumberString();
  200. if (!float.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out number))
  201. return 0;
  202. return number;
  203. }
  204. public double ParseDoubleNumber () {
  205. double number;
  206. var str = GetNumberString();
  207. if (!double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out number))
  208. return 0;
  209. return number;
  210. }
  211. int GetLastIndexOfNumber (int index) {
  212. int lastIndex;
  213. for (lastIndex = index; lastIndex < json.Length; lastIndex++) {
  214. char ch = json[lastIndex];
  215. if ((ch < '0' || ch > '9') && ch != '+' && ch != '-'
  216. && ch != '.' && ch != 'e' && ch != 'E')
  217. break;
  218. }
  219. return lastIndex - 1;
  220. }
  221. void SkipWhiteSpaces () {
  222. for (; index < json.Length; index++) {
  223. char ch = json[index];
  224. if (ch == '\n')
  225. lineNumber++;
  226. if (!char.IsWhiteSpace(json[index]))
  227. break;
  228. }
  229. }
  230. public Token LookAhead () {
  231. SkipWhiteSpaces();
  232. int savedIndex = index;
  233. return NextToken(json, ref savedIndex);
  234. }
  235. public Token NextToken () {
  236. SkipWhiteSpaces();
  237. return NextToken(json, ref index);
  238. }
  239. static Token NextToken (char[] json, ref int index) {
  240. if (index == json.Length)
  241. return Token.None;
  242. char c = json[index++];
  243. switch (c) {
  244. case '{':
  245. return Token.CurlyOpen;
  246. case '}':
  247. return Token.CurlyClose;
  248. case '[':
  249. return Token.SquaredOpen;
  250. case ']':
  251. return Token.SquaredClose;
  252. case ',':
  253. return Token.Comma;
  254. case '"':
  255. return Token.String;
  256. case '0':
  257. case '1':
  258. case '2':
  259. case '3':
  260. case '4':
  261. case '5':
  262. case '6':
  263. case '7':
  264. case '8':
  265. case '9':
  266. case '-':
  267. return Token.Number;
  268. case ':':
  269. return Token.Colon;
  270. }
  271. index--;
  272. int remainingLength = json.Length - index;
  273. // false
  274. if (remainingLength >= 5) {
  275. if (json[index] == 'f' &&
  276. json[index + 1] == 'a' &&
  277. json[index + 2] == 'l' &&
  278. json[index + 3] == 's' &&
  279. json[index + 4] == 'e') {
  280. index += 5;
  281. return Token.False;
  282. }
  283. }
  284. // true
  285. if (remainingLength >= 4) {
  286. if (json[index] == 't' &&
  287. json[index + 1] == 'r' &&
  288. json[index + 2] == 'u' &&
  289. json[index + 3] == 'e') {
  290. index += 4;
  291. return Token.True;
  292. }
  293. }
  294. // null
  295. if (remainingLength >= 4) {
  296. if (json[index] == 'n' &&
  297. json[index + 1] == 'u' &&
  298. json[index + 2] == 'l' &&
  299. json[index + 3] == 'l') {
  300. index += 4;
  301. return Token.Null;
  302. }
  303. }
  304. return Token.None;
  305. }
  306. }
  307. public class JsonDecoder {
  308. public string errorMessage {
  309. get;
  310. private set;
  311. }
  312. public bool parseNumbersAsFloat {
  313. get;
  314. set;
  315. }
  316. Lexer lexer;
  317. public JsonDecoder () {
  318. errorMessage = null;
  319. parseNumbersAsFloat = false;
  320. }
  321. public object Decode (string text) {
  322. errorMessage = null;
  323. lexer = new Lexer(text);
  324. lexer.parseNumbersAsFloat = parseNumbersAsFloat;
  325. return ParseValue();
  326. }
  327. public static object DecodeText (string text) {
  328. var builder = new JsonDecoder();
  329. return builder.Decode(text);
  330. }
  331. IDictionary<string, object> ParseObject () {
  332. var table = new Dictionary<string, object>();
  333. // {
  334. lexer.NextToken();
  335. while (true) {
  336. var token = lexer.LookAhead();
  337. switch (token) {
  338. case Lexer.Token.None:
  339. TriggerError("Invalid token");
  340. return null;
  341. case Lexer.Token.Comma:
  342. lexer.NextToken();
  343. break;
  344. case Lexer.Token.CurlyClose:
  345. lexer.NextToken();
  346. return table;
  347. default:
  348. // name
  349. string name = EvalLexer(lexer.ParseString());
  350. if (errorMessage != null)
  351. return null;
  352. // :
  353. token = lexer.NextToken();
  354. if (token != Lexer.Token.Colon) {
  355. TriggerError("Invalid token; expected ':'");
  356. return null;
  357. }
  358. // value
  359. object value = ParseValue();
  360. if (errorMessage != null)
  361. return null;
  362. table[name] = value;
  363. break;
  364. }
  365. }
  366. //return null; // Unreachable code
  367. }
  368. IList<object> ParseArray () {
  369. var array = new List<object>();
  370. // [
  371. lexer.NextToken();
  372. while (true) {
  373. var token = lexer.LookAhead();
  374. switch (token) {
  375. case Lexer.Token.None:
  376. TriggerError("Invalid token");
  377. return null;
  378. case Lexer.Token.Comma:
  379. lexer.NextToken();
  380. break;
  381. case Lexer.Token.SquaredClose:
  382. lexer.NextToken();
  383. return array;
  384. default:
  385. object value = ParseValue();
  386. if (errorMessage != null)
  387. return null;
  388. array.Add(value);
  389. break;
  390. }
  391. }
  392. //return null; // Unreachable code
  393. }
  394. object ParseValue () {
  395. switch (lexer.LookAhead()) {
  396. case Lexer.Token.String:
  397. return EvalLexer(lexer.ParseString());
  398. case Lexer.Token.Number:
  399. if (parseNumbersAsFloat)
  400. return EvalLexer(lexer.ParseFloatNumber());
  401. else
  402. return EvalLexer(lexer.ParseDoubleNumber());
  403. case Lexer.Token.CurlyOpen:
  404. return ParseObject();
  405. case Lexer.Token.SquaredOpen:
  406. return ParseArray();
  407. case Lexer.Token.True:
  408. lexer.NextToken();
  409. return true;
  410. case Lexer.Token.False:
  411. lexer.NextToken();
  412. return false;
  413. case Lexer.Token.Null:
  414. lexer.NextToken();
  415. return null;
  416. case Lexer.Token.None:
  417. break;
  418. }
  419. TriggerError("Unable to parse value");
  420. return null;
  421. }
  422. void TriggerError (string message) {
  423. errorMessage = string.Format("Error: '{0}' at line {1}",
  424. message, lexer.lineNumber);
  425. }
  426. T EvalLexer<T> (T value) {
  427. if (lexer.hasError)
  428. TriggerError("Lexical error ocurred");
  429. return value;
  430. }
  431. }
  432. }