3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
8 import java.io.StringReader;
11 Copyright (c) 2002 JSON.org
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
23 The Software shall be used for Good, not Evil.
25 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35 * A JSONTokener takes a source string and extracts characters and tokens from
36 * it. It is used by the JSONObject and JSONArray constructors to parse
37 * JSON source strings.
41 public class JSONTokener {
43 private long character;
47 private char previous;
48 private Reader reader;
49 private boolean usePrevious;
53 * Construct a JSONTokener from a Reader.
55 * @param reader A reader.
57 public JSONTokener(Reader reader) {
58 this.reader = reader.markSupported()
60 : new BufferedReader(reader);
62 this.usePrevious = false;
71 * Construct a JSONTokener from an InputStream.
72 * @param inputStream The source.
74 public JSONTokener(InputStream inputStream) {
75 this(new InputStreamReader(inputStream));
80 * Construct a JSONTokener from a string.
82 * @param s A source string.
84 public JSONTokener(String s) {
85 this(new StringReader(s));
90 * Back up one character. This provides a sort of lookahead capability,
91 * so that you can test for a digit or letter before attempting to parse
92 * the next number or identifier.
93 * @throws JSONException Thrown if trying to step back more than 1 step
94 * or if already at the start of the string
96 public void back() throws JSONException {
97 if (this.usePrevious || this.index <= 0) {
98 throw new JSONException("Stepping back two steps is not supported");
102 this.usePrevious = true;
108 * Get the hex value of a character (base16).
109 * @param c A character between '0' and '9' or between 'A' and 'F' or
110 * between 'a' and 'f'.
111 * @return An int between 0 and 15, or -1 if c was not a hex digit.
113 public static int dehexchar(char c) {
114 if (c >= '0' && c <= '9') {
117 if (c >= 'A' && c <= 'F') {
118 return c - ('A' - 10);
120 if (c >= 'a' && c <= 'f') {
121 return c - ('a' - 10);
127 * @return true if at the end of the file and we didn't step back
129 public boolean end() {
130 return this.eof && !this.usePrevious;
135 * Determine if the source string still contains characters that next()
137 * @return true if not yet at the end of the source.
138 * @throws JSONException thrown if there is an error stepping forward
139 * or backward while checking for more data.
141 public boolean more() throws JSONException {
152 * Get the next character in the source string.
154 * @return The next character, or 0 if past the end of the source string.
155 * @throws JSONException Thrown if there is an error reading the source string.
157 public char next() throws JSONException {
159 if (this.usePrevious) {
160 this.usePrevious = false;
164 c = this.reader.read();
165 } catch (IOException exception) {
166 throw new JSONException(exception);
169 if (c <= 0) { // End of stream
175 if (this.previous == '\r') {
177 this.character = c == '\n' ? 0 : 1;
178 } else if (c == '\n') {
184 this.previous = (char) c;
185 return this.previous;
190 * Consume the next character, and check that it matches a specified
192 * @param c The character to match.
193 * @return The character.
194 * @throws JSONException if the character does not match.
196 public char next(char c) throws JSONException {
197 char n = this.next();
199 throw this.syntaxError("Expected '" + c + "' and instead saw '" +
207 * Get the next n characters.
209 * @param n The number of characters to take.
210 * @return A string of n characters.
211 * @throws JSONException
212 * Substring bounds error if there are not
213 * n characters remaining in the source string.
215 public String next(int n) throws JSONException {
220 char[] chars = new char[n];
224 chars[pos] = this.next();
226 throw this.syntaxError("Substring bounds error");
230 return new String(chars);
235 * Get the next char in the string, skipping whitespace.
236 * @throws JSONException Thrown if there is an error reading the source string.
237 * @return A character, or 0 if there are no more characters.
239 public char nextClean() throws JSONException {
241 char c = this.next();
242 if (c == 0 || c > ' ') {
250 * Return the characters up to the next close quote character.
251 * Backslash processing is done. The formal JSON format does not
252 * allow strings in single quotes, but an implementation is allowed to
254 * @param quote The quoting character, either
255 * <code>"</code> <small>(double quote)</small> or
256 * <code>'</code> <small>(single quote)</small>.
258 * @throws JSONException Unterminated string.
260 public String nextString(char quote) throws JSONException {
262 StringBuilder sb = new StringBuilder();
269 throw this.syntaxError("Unterminated string");
290 sb.append((char)Integer.parseInt(this.next(4), 16));
291 } catch (NumberFormatException e) {
292 throw this.syntaxError("Illegal escape.", e);
302 throw this.syntaxError("Illegal escape.");
307 return sb.toString();
316 * Get the text up but not including the specified character or the
317 * end of line, whichever comes first.
318 * @param delimiter A delimiter character.
320 * @throws JSONException Thrown if there is an error while searching
323 public String nextTo(char delimiter) throws JSONException {
324 StringBuilder sb = new StringBuilder();
326 char c = this.next();
327 if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
331 return sb.toString().trim();
339 * Get the text up but not including one of the specified delimiter
340 * characters or the end of line, whichever comes first.
341 * @param delimiters A set of delimiter characters.
342 * @return A string, trimmed.
343 * @throws JSONException Thrown if there is an error while searching
346 public String nextTo(String delimiters) throws JSONException {
348 StringBuilder sb = new StringBuilder();
351 if (delimiters.indexOf(c) >= 0 || c == 0 ||
352 c == '\n' || c == '\r') {
356 return sb.toString().trim();
364 * Get the next value. The value can be a Boolean, Double, Integer,
365 * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
366 * @throws JSONException If syntax error.
370 public Object nextValue() throws JSONException {
371 char c = this.nextClean();
377 return this.nextString(c);
380 return new JSONObject(this);
383 return new JSONArray(this);
387 * Handle unquoted text. This could be the values true, false, or
388 * null, or it can be a number. An implementation (such as this one)
389 * is allowed to also accept non-standard forms.
391 * Accumulate characters until we reach the end of the text or a
392 * formatting character.
395 StringBuilder sb = new StringBuilder();
396 while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
402 string = sb.toString().trim();
403 if ("".equals(string)) {
404 throw this.syntaxError("Missing value");
406 return JSONObject.stringToValue(string);
411 * Skip characters until the next character is the requested character.
412 * If the requested character is not found, no characters are skipped.
413 * @param to A character to skip to.
414 * @return The requested character, or zero if the requested character
416 * @throws JSONException Thrown if there is an error while searching
417 * for the to character
419 public char skipTo(char to) throws JSONException {
422 long startIndex = this.index;
423 long startCharacter = this.character;
424 long startLine = this.line;
425 this.reader.mark(1000000);
430 this.index = startIndex;
431 this.character = startCharacter;
432 this.line = startLine;
436 } catch (IOException exception) {
437 throw new JSONException(exception);
445 * Make a JSONException to signal a syntax error.
447 * @param message The error message.
448 * @return A JSONException object, suitable for throwing
450 public JSONException syntaxError(String message) {
451 return new JSONException(message + this.toString());
455 * Make a JSONException to signal a syntax error.
457 * @param message The error message.
458 * @param causedBy The throwable that caused the error.
459 * @return A JSONException object, suitable for throwing
461 public JSONException syntaxError(String message, Throwable causedBy) {
462 return new JSONException(message + this.toString(), causedBy);
466 * Make a printable string of this JSONTokener.
468 * @return " at {index} [character {character} line {line}]"
471 public String toString() {
472 return " at " + this.index + " [character " + this.character + " line " +