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 JSON
42 public class JSONTokener
44 /** current read character position on the current line. */
45 private long character;
47 /** flag to indicate if the end of the input has been found. */
50 /** current read index of the input. */
53 /** current line of the input. */
56 /** previous character read from the input. */
57 private char previous;
59 /** Reader for the input. */
60 private final Reader reader;
62 /** flag to indicate that a previous character was requested. */
63 private boolean usePrevious;
65 /** the number of characters read in the previous line. */
66 private long characterPreviousLine;
69 * Construct a JSONTokener from a Reader. The caller must close the Reader.
74 public JSONTokener(Reader reader)
76 this.reader = reader.markSupported() ? reader
77 : new BufferedReader(reader);
79 this.usePrevious = false;
83 this.characterPreviousLine = 0;
88 * Construct a JSONTokener from an InputStream. The caller must close the
94 public JSONTokener(InputStream inputStream)
96 this(new InputStreamReader(inputStream));
100 * Construct a JSONTokener from a string.
105 public JSONTokener(String s)
107 this(new StringReader(s));
111 * Back up one character. This provides a sort of lookahead capability, so
112 * that you can test for a digit or letter before attempting to parse the next
113 * number or identifier.
115 * @throws JSONException
116 * Thrown if trying to step back more than 1 step or if already at
117 * the start of the string
119 public void back() throws JSONException
121 if (this.usePrevious || this.index <= 0)
123 throw new JSONException("Stepping back two steps is not supported");
125 this.decrementIndexes();
126 this.usePrevious = true;
131 * Decrements the indexes for the {@link #back()} method based on the previous
134 private void decrementIndexes()
137 if (this.previous == '\r' || this.previous == '\n')
140 this.character = this.characterPreviousLine;
142 else if (this.character > 0)
149 * Get the hex value of a character (base16).
152 * A character between '0' and '9' or between 'A' and 'F' or between
154 * @return An int between 0 and 15, or -1 if c was not a hex digit.
156 public static int dehexchar(char c)
158 if (c >= '0' && c <= '9')
162 if (c >= 'A' && c <= 'F')
164 return c - ('A' - 10);
166 if (c >= 'a' && c <= 'f')
168 return c - ('a' - 10);
174 * Checks if the end of the input has been reached.
176 * @return true if at the end of the file and we didn't step back
180 return this.eof && !this.usePrevious;
184 * Determine if the source string still contains characters that next() can
187 * @return true if not yet at the end of the source.
188 * @throws JSONException
189 * thrown if there is an error stepping forward or backward while
190 * checking for more data.
192 public boolean more() throws JSONException
194 if (this.usePrevious)
201 } catch (IOException e)
203 throw new JSONException("Unable to preserve stream position", e);
207 // -1 is EOF, but next() can not consume the null character '\0'
208 if (this.reader.read() <= 0)
214 } catch (IOException e)
216 throw new JSONException(
217 "Unable to read the next character from the stream", e);
223 * Get the next character in the source string.
225 * @return The next character, or 0 if past the end of the source string.
226 * @throws JSONException
227 * Thrown if there is an error reading the source string.
229 public char next() throws JSONException
232 if (this.usePrevious)
234 this.usePrevious = false;
241 c = this.reader.read();
242 } catch (IOException exception)
244 throw new JSONException(exception);
252 this.incrementIndexes(c);
253 this.previous = (char) c;
254 return this.previous;
258 * Increments the internal indexes according to the previous character read
259 * and the character passed as the current character.
262 * the current character read.
264 private void incrementIndexes(int c)
272 this.characterPreviousLine = this.character;
277 if (this.previous != '\r')
280 this.characterPreviousLine = this.character;
292 * Consume the next character, and check that it matches a specified
296 * The character to match.
297 * @return The character.
298 * @throws JSONException
299 * if the character does not match.
301 public char next(char c) throws JSONException
303 char n = this.next();
308 throw this.syntaxError(
309 "Expected '" + c + "' and instead saw '" + n + "'");
311 throw this.syntaxError("Expected '" + c + "' and instead saw ''");
317 * Get the next n characters.
320 * The number of characters to take.
321 * @return A string of n characters.
322 * @throws JSONException
323 * Substring bounds error if there are not n characters remaining in
326 public String next(int n) throws JSONException
333 char[] chars = new char[n];
338 chars[pos] = this.next();
341 throw this.syntaxError("Substring bounds error");
345 return new String(chars);
349 * Get the next char in the string, skipping whitespace.
351 * @throws JSONException
352 * Thrown if there is an error reading the source string.
353 * @return A character, or 0 if there are no more characters.
355 public char nextClean() throws JSONException
359 char c = this.next();
360 if (c == 0 || c > ' ')
368 * Return the characters up to the next close quote character. Backslash
369 * processing is done. The formal JSON format does not allow strings in single
370 * quotes, but an implementation is allowed to accept them.
373 * The quoting character, either <code>"</code> <small>(double
374 * quote)</small> or <code>'</code> <small>(single
377 * @throws JSONException
378 * Unterminated string.
380 public String nextString(char quote) throws JSONException
383 StringBuilder sb = new StringBuilder();
392 throw this.syntaxError("Unterminated string");
415 sb.append((char) Integer.parseInt(this.next(4), 16));
416 } catch (NumberFormatException e)
418 throw this.syntaxError("Illegal escape.", e);
428 throw this.syntaxError("Illegal escape.");
434 return sb.toString();
442 * Get the text up but not including the specified character or the end of
443 * line, whichever comes first.
446 * A delimiter character.
448 * @throws JSONException
449 * Thrown if there is an error while searching for the delimiter
451 public String nextTo(char delimiter) throws JSONException
453 StringBuilder sb = new StringBuilder();
456 char c = this.next();
457 if (c == delimiter || c == 0 || c == '\n' || c == '\r')
463 return sb.toString().trim();
470 * Get the text up but not including one of the specified delimiter characters
471 * or the end of line, whichever comes first.
474 * A set of delimiter characters.
475 * @return A string, trimmed.
476 * @throws JSONException
477 * Thrown if there is an error while searching for the delimiter
479 public String nextTo(String delimiters) throws JSONException
482 StringBuilder sb = new StringBuilder();
486 if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r')
492 return sb.toString().trim();
499 * Get the next value. The value can be a Boolean, Double, Integer, JSONArray,
500 * JSONObject, Long, or String, or the JSONObject.NULL object.
502 * @throws JSONException
507 public Object nextValue() throws JSONException
509 char c = this.nextClean();
516 return this.nextString(c);
519 return new JSONObject(this);
522 return new JSONArray(this);
526 * Handle unquoted text. This could be the values true, false, or
527 * null, or it can be a number. An implementation (such as this one)
528 * is allowed to also accept non-standard forms.
530 * Accumulate characters until we reach the end of the text or a
531 * formatting character.
534 StringBuilder sb = new StringBuilder();
535 while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0)
542 string = sb.toString().trim();
543 if ("".equals(string))
545 throw this.syntaxError("Missing value");
547 return JSONObject.stringToValue(string);
551 * Skip characters until the next character is the requested character. If the
552 * requested character is not found, no characters are skipped.
555 * A character to skip to.
556 * @return The requested character, or zero if the requested character is not
558 * @throws JSONException
559 * Thrown if there is an error while searching for the to character
561 public char skipTo(char to) throws JSONException
566 long startIndex = this.index;
567 long startCharacter = this.character;
568 long startLine = this.line;
569 this.reader.mark(1000000);
575 // in some readers, reset() may throw an exception if
576 // the remaining portion of the input is greater than
577 // the mark size (1,000,000 above).
579 this.index = startIndex;
580 this.character = startCharacter;
581 this.line = startLine;
586 } catch (IOException exception)
588 throw new JSONException(exception);
595 * Make a JSONException to signal a syntax error.
599 * @return A JSONException object, suitable for throwing
601 public JSONException syntaxError(String message)
603 return new JSONException(message + this.toString());
607 * Make a JSONException to signal a syntax error.
612 * The throwable that caused the error.
613 * @return A JSONException object, suitable for throwing
615 public JSONException syntaxError(String message, Throwable causedBy)
617 return new JSONException(message + this.toString(), causedBy);
621 * Make a printable string of this JSONTokener.
623 * @return " at {index} [character {character} line {line}]"
626 public String toString()
628 return " at " + this.index + " [character " + this.character + " line "