Java IRC bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JSONTokener.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. package org.json;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.Reader;
  5. import java.io.StringReader;
  6. /*
  7. Copyright (c) 2002 JSON.org
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16. The Software shall be used for Good, not Evil.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25. /**
  26. * A JSONTokener takes a source string and extracts characters and tokens from
  27. * it. It is used by the JSONObject and JSONArray constructors to parse
  28. * JSON source strings.
  29. * @author JSON.org
  30. * @version 2008-09-18
  31. */
  32. public class JSONTokener {
  33. private int index;
  34. private Reader reader;
  35. private char lastChar;
  36. private boolean useLastChar;
  37. /**
  38. * Construct a JSONTokener from a string.
  39. *
  40. * @param reader A reader.
  41. */
  42. public JSONTokener(Reader reader) {
  43. this.reader = reader.markSupported() ?
  44. reader : new BufferedReader(reader);
  45. this.useLastChar = false;
  46. this.index = 0;
  47. }
  48. /**
  49. * Construct a JSONTokener from a string.
  50. *
  51. * @param s A source string.
  52. */
  53. public JSONTokener(String s) {
  54. this(new StringReader(s));
  55. }
  56. /**
  57. * Back up one character. This provides a sort of lookahead capability,
  58. * so that you can test for a digit or letter before attempting to parse
  59. * the next number or identifier.
  60. */
  61. public void back() throws JSONException {
  62. if (useLastChar || index <= 0) {
  63. throw new JSONException("Stepping back two steps is not supported");
  64. }
  65. index -= 1;
  66. useLastChar = true;
  67. }
  68. /**
  69. * Get the hex value of a character (base16).
  70. * @param c A character between '0' and '9' or between 'A' and 'F' or
  71. * between 'a' and 'f'.
  72. * @return An int between 0 and 15, or -1 if c was not a hex digit.
  73. */
  74. public static int dehexchar(char c) {
  75. if (c >= '0' && c <= '9') {
  76. return c - '0';
  77. }
  78. if (c >= 'A' && c <= 'F') {
  79. return c - ('A' - 10);
  80. }
  81. if (c >= 'a' && c <= 'f') {
  82. return c - ('a' - 10);
  83. }
  84. return -1;
  85. }
  86. /**
  87. * Determine if the source string still contains characters that next()
  88. * can consume.
  89. * @return true if not yet at the end of the source.
  90. */
  91. public boolean more() throws JSONException {
  92. char nextChar = next();
  93. if (nextChar == 0) {
  94. return false;
  95. }
  96. back();
  97. return true;
  98. }
  99. /**
  100. * Get the next character in the source string.
  101. *
  102. * @return The next character, or 0 if past the end of the source string.
  103. */
  104. public char next() throws JSONException {
  105. if (this.useLastChar) {
  106. this.useLastChar = false;
  107. if (this.lastChar != 0) {
  108. this.index += 1;
  109. }
  110. return this.lastChar;
  111. }
  112. int c;
  113. try {
  114. c = this.reader.read();
  115. } catch (IOException exc) {
  116. throw new JSONException(exc);
  117. }
  118. if (c <= 0) { // End of stream
  119. this.lastChar = 0;
  120. return 0;
  121. }
  122. this.index += 1;
  123. this.lastChar = (char) c;
  124. return this.lastChar;
  125. }
  126. /**
  127. * Consume the next character, and check that it matches a specified
  128. * character.
  129. * @param c The character to match.
  130. * @return The character.
  131. * @throws JSONException if the character does not match.
  132. */
  133. public char next(char c) throws JSONException {
  134. char n = next();
  135. if (n != c) {
  136. throw syntaxError("Expected '" + c + "' and instead saw '" +
  137. n + "'");
  138. }
  139. return n;
  140. }
  141. /**
  142. * Get the next n characters.
  143. *
  144. * @param n The number of characters to take.
  145. * @return A string of n characters.
  146. * @throws JSONException
  147. * Substring bounds error if there are not
  148. * n characters remaining in the source string.
  149. */
  150. public String next(int n) throws JSONException {
  151. if (n == 0) {
  152. return "";
  153. }
  154. char[] buffer = new char[n];
  155. int pos = 0;
  156. if (this.useLastChar) {
  157. this.useLastChar = false;
  158. buffer[0] = this.lastChar;
  159. pos = 1;
  160. }
  161. try {
  162. int len;
  163. while ((pos < n) && ((len = reader.read(buffer, pos, n - pos)) != -1)) {
  164. pos += len;
  165. }
  166. } catch (IOException exc) {
  167. throw new JSONException(exc);
  168. }
  169. this.index += pos;
  170. if (pos < n) {
  171. throw syntaxError("Substring bounds error");
  172. }
  173. this.lastChar = buffer[n - 1];
  174. return new String(buffer);
  175. }
  176. /**
  177. * Get the next char in the string, skipping whitespace.
  178. * @throws JSONException
  179. * @return A character, or 0 if there are no more characters.
  180. */
  181. public char nextClean() throws JSONException {
  182. for (;;) {
  183. char c = next();
  184. if (c == 0 || c > ' ') {
  185. return c;
  186. }
  187. }
  188. }
  189. /**
  190. * Return the characters up to the next close quote character.
  191. * Backslash processing is done. The formal JSON format does not
  192. * allow strings in single quotes, but an implementation is allowed to
  193. * accept them.
  194. * @param quote The quoting character, either
  195. * <code>"</code>&nbsp;<small>(double quote)</small> or
  196. * <code>'</code>&nbsp;<small>(single quote)</small>.
  197. * @return A String.
  198. * @throws JSONException Unterminated string.
  199. */
  200. public String nextString(char quote) throws JSONException {
  201. char c;
  202. StringBuffer sb = new StringBuffer();
  203. for (;;) {
  204. c = next();
  205. switch (c) {
  206. case 0:
  207. case '\n':
  208. case '\r':
  209. throw syntaxError("Unterminated string");
  210. case '\\':
  211. c = next();
  212. switch (c) {
  213. case 'b':
  214. sb.append('\b');
  215. break;
  216. case 't':
  217. sb.append('\t');
  218. break;
  219. case 'n':
  220. sb.append('\n');
  221. break;
  222. case 'f':
  223. sb.append('\f');
  224. break;
  225. case 'r':
  226. sb.append('\r');
  227. break;
  228. case 'u':
  229. sb.append((char)Integer.parseInt(next(4), 16));
  230. break;
  231. case 'x' :
  232. sb.append((char) Integer.parseInt(next(2), 16));
  233. break;
  234. default:
  235. sb.append(c);
  236. }
  237. break;
  238. default:
  239. if (c == quote) {
  240. return sb.toString();
  241. }
  242. sb.append(c);
  243. }
  244. }
  245. }
  246. /**
  247. * Get the text up but not including the specified character or the
  248. * end of line, whichever comes first.
  249. * @param d A delimiter character.
  250. * @return A string.
  251. */
  252. public String nextTo(char d) throws JSONException {
  253. StringBuffer sb = new StringBuffer();
  254. for (;;) {
  255. char c = next();
  256. if (c == d || c == 0 || c == '\n' || c == '\r') {
  257. if (c != 0) {
  258. back();
  259. }
  260. return sb.toString().trim();
  261. }
  262. sb.append(c);
  263. }
  264. }
  265. /**
  266. * Get the text up but not including one of the specified delimiter
  267. * characters or the end of line, whichever comes first.
  268. * @param delimiters A set of delimiter characters.
  269. * @return A string, trimmed.
  270. */
  271. public String nextTo(String delimiters) throws JSONException {
  272. char c;
  273. StringBuffer sb = new StringBuffer();
  274. for (;;) {
  275. c = next();
  276. if (delimiters.indexOf(c) >= 0 || c == 0 ||
  277. c == '\n' || c == '\r') {
  278. if (c != 0) {
  279. back();
  280. }
  281. return sb.toString().trim();
  282. }
  283. sb.append(c);
  284. }
  285. }
  286. /**
  287. * Get the next value. The value can be a Boolean, Double, Integer,
  288. * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
  289. * @throws JSONException If syntax error.
  290. *
  291. * @return An object.
  292. */
  293. public Object nextValue() throws JSONException {
  294. char c = nextClean();
  295. String s;
  296. switch (c) {
  297. case '"':
  298. case '\'':
  299. return nextString(c);
  300. case '{':
  301. back();
  302. return new JSONObject(this);
  303. case '[':
  304. case '(':
  305. back();
  306. return new JSONArray(this);
  307. }
  308. /*
  309. * Handle unquoted text. This could be the values true, false, or
  310. * null, or it can be a number. An implementation (such as this one)
  311. * is allowed to also accept non-standard forms.
  312. *
  313. * Accumulate characters until we reach the end of the text or a
  314. * formatting character.
  315. */
  316. StringBuffer sb = new StringBuffer();
  317. while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
  318. sb.append(c);
  319. c = next();
  320. }
  321. back();
  322. s = sb.toString().trim();
  323. if (s.equals("")) {
  324. throw syntaxError("Missing value");
  325. }
  326. return JSONObject.stringToValue(s);
  327. }
  328. /**
  329. * Skip characters until the next character is the requested character.
  330. * If the requested character is not found, no characters are skipped.
  331. * @param to A character to skip to.
  332. * @return The requested character, or zero if the requested character
  333. * is not found.
  334. */
  335. public char skipTo(char to) throws JSONException {
  336. char c;
  337. try {
  338. int startIndex = this.index;
  339. reader.mark(Integer.MAX_VALUE);
  340. do {
  341. c = next();
  342. if (c == 0) {
  343. reader.reset();
  344. this.index = startIndex;
  345. return c;
  346. }
  347. } while (c != to);
  348. } catch (IOException exc) {
  349. throw new JSONException(exc);
  350. }
  351. back();
  352. return c;
  353. }
  354. /**
  355. * Make a JSONException to signal a syntax error.
  356. *
  357. * @param message The error message.
  358. * @return A JSONException object, suitable for throwing
  359. */
  360. public JSONException syntaxError(String message) {
  361. return new JSONException(message + toString());
  362. }
  363. /**
  364. * Make a printable string of this JSONTokener.
  365. *
  366. * @return " at character [this.index]"
  367. */
  368. public String toString() {
  369. return " at character " + index;
  370. }
  371. }