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 {
42 /** current read character position on the current line. */
43 private long character;
44 /** flag to indicate if the end of the input has been found. */
46 /** current read index of the input. */
48 /** current line of the input. */
50 /** previous character read from the input. */
51 private char previous;
52 /** Reader for the input. */
53 private final Reader reader;
54 /** flag to indicate that a previous character was requested. */
55 private boolean usePrevious;
56 /** the number of characters read in the previous line. */
57 private long characterPreviousLine;
61 * Construct a JSONTokener from a Reader. The caller must close the Reader.
63 * @param reader A reader.
65 public JSONTokener(Reader reader) {
66 this.reader = reader.markSupported()
68 : new BufferedReader(reader);
70 this.usePrevious = false;
74 this.characterPreviousLine = 0;
80 * Construct a JSONTokener from an InputStream. The caller must close the input stream.
81 * @param inputStream The source.
83 public JSONTokener(InputStream inputStream) {
84 this(new InputStreamReader(inputStream));
89 * Construct a JSONTokener from a string.
91 * @param s A source string.
93 public JSONTokener(String s) {
94 this(new StringReader(s));
99 * Back up one character. This provides a sort of lookahead capability,
100 * so that you can test for a digit or letter before attempting to parse
101 * the next number or identifier.
102 * @throws JSONException Thrown if trying to step back more than 1 step
103 * or if already at the start of the string
105 public void back() throws JSONException {
106 if (this.usePrevious || this.index <= 0) {
107 throw new JSONException("Stepping back two steps is not supported");
109 this.decrementIndexes();
110 this.usePrevious = true;
115 * Decrements the indexes for the {@link #back()} method based on the previous character read.
117 private void decrementIndexes() {
119 if(this.previous=='\r' || this.previous == '\n') {
121 this.character=this.characterPreviousLine ;
122 } else if(this.character > 0){
128 * Get the hex value of a character (base16).
129 * @param c A character between '0' and '9' or between 'A' and 'F' or
130 * between 'a' and 'f'.
131 * @return An int between 0 and 15, or -1 if c was not a hex digit.
133 public static int dehexchar(char c) {
134 if (c >= '0' && c <= '9') {
137 if (c >= 'A' && c <= 'F') {
138 return c - ('A' - 10);
140 if (c >= 'a' && c <= 'f') {
141 return c - ('a' - 10);
147 * Checks if the end of the input has been reached.
149 * @return true if at the end of the file and we didn't step back
151 public boolean end() {
152 return this.eof && !this.usePrevious;
157 * Determine if the source string still contains characters that next()
159 * @return true if not yet at the end of the source.
160 * @throws JSONException thrown if there is an error stepping forward
161 * or backward while checking for more data.
163 public boolean more() throws JSONException {
164 if(this.usePrevious) {
169 } catch (IOException e) {
170 throw new JSONException("Unable to preserve stream position", e);
173 // -1 is EOF, but next() can not consume the null character '\0'
174 if(this.reader.read() <= 0) {
179 } catch (IOException e) {
180 throw new JSONException("Unable to read the next character from the stream", e);
187 * Get the next character in the source string.
189 * @return The next character, or 0 if past the end of the source string.
190 * @throws JSONException Thrown if there is an error reading the source string.
192 public char next() throws JSONException {
194 if (this.usePrevious) {
195 this.usePrevious = false;
199 c = this.reader.read();
200 } catch (IOException exception) {
201 throw new JSONException(exception);
204 if (c <= 0) { // End of stream
208 this.incrementIndexes(c);
209 this.previous = (char) c;
210 return this.previous;
214 * Increments the internal indexes according to the previous character
215 * read and the character passed as the current character.
216 * @param c the current character read.
218 private void incrementIndexes(int c) {
223 this.characterPreviousLine = this.character;
226 if(this.previous != '\r') {
228 this.characterPreviousLine = this.character;
238 * Consume the next character, and check that it matches a specified
240 * @param c The character to match.
241 * @return The character.
242 * @throws JSONException if the character does not match.
244 public char next(char c) throws JSONException {
245 char n = this.next();
248 throw this.syntaxError("Expected '" + c + "' and instead saw '" +
251 throw this.syntaxError("Expected '" + c + "' and instead saw ''");
258 * Get the next n characters.
260 * @param n The number of characters to take.
261 * @return A string of n characters.
262 * @throws JSONException
263 * Substring bounds error if there are not
264 * n characters remaining in the source string.
266 public String next(int n) throws JSONException {
271 char[] chars = new char[n];
275 chars[pos] = this.next();
277 throw this.syntaxError("Substring bounds error");
281 return new String(chars);
286 * Get the next char in the string, skipping whitespace.
287 * @throws JSONException Thrown if there is an error reading the source string.
288 * @return A character, or 0 if there are no more characters.
290 public char nextClean() throws JSONException {
292 char c = this.next();
293 if (c == 0 || c > ' ') {
301 * Return the characters up to the next close quote character.
302 * Backslash processing is done. The formal JSON format does not
303 * allow strings in single quotes, but an implementation is allowed to
305 * @param quote The quoting character, either
306 * <code>"</code> <small>(double quote)</small> or
307 * <code>'</code> <small>(single quote)</small>.
309 * @throws JSONException Unterminated string.
311 public String nextString(char quote) throws JSONException {
313 StringBuilder sb = new StringBuilder();
320 throw this.syntaxError("Unterminated string");
341 sb.append((char)Integer.parseInt(this.next(4), 16));
342 } catch (NumberFormatException e) {
343 throw this.syntaxError("Illegal escape.", e);
353 throw this.syntaxError("Illegal escape.");
358 return sb.toString();
367 * Get the text up but not including the specified character or the
368 * end of line, whichever comes first.
369 * @param delimiter A delimiter character.
371 * @throws JSONException Thrown if there is an error while searching
374 public String nextTo(char delimiter) throws JSONException {
375 StringBuilder sb = new StringBuilder();
377 char c = this.next();
378 if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
382 return sb.toString().trim();
390 * Get the text up but not including one of the specified delimiter
391 * characters or the end of line, whichever comes first.
392 * @param delimiters A set of delimiter characters.
393 * @return A string, trimmed.
394 * @throws JSONException Thrown if there is an error while searching
397 public String nextTo(String delimiters) throws JSONException {
399 StringBuilder sb = new StringBuilder();
402 if (delimiters.indexOf(c) >= 0 || c == 0 ||
403 c == '\n' || c == '\r') {
407 return sb.toString().trim();
415 * Get the next value. The value can be a Boolean, Double, Integer,
416 * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
417 * @throws JSONException If syntax error.
421 public Object nextValue() throws JSONException {
422 char c = this.nextClean();
428 return this.nextString(c);
431 return new JSONObject(this);
434 return new JSONArray(this);
438 * Handle unquoted text. This could be the values true, false, or
439 * null, or it can be a number. An implementation (such as this one)
440 * is allowed to also accept non-standard forms.
442 * Accumulate characters until we reach the end of the text or a
443 * formatting character.
446 StringBuilder sb = new StringBuilder();
447 while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
453 string = sb.toString().trim();
454 if ("".equals(string)) {
455 throw this.syntaxError("Missing value");
457 return JSONObject.stringToValue(string);
462 * Skip characters until the next character is the requested character.
463 * If the requested character is not found, no characters are skipped.
464 * @param to A character to skip to.
465 * @return The requested character, or zero if the requested character
467 * @throws JSONException Thrown if there is an error while searching
468 * for the to character
470 public char skipTo(char to) throws JSONException {
473 long startIndex = this.index;
474 long startCharacter = this.character;
475 long startLine = this.line;
476 this.reader.mark(1000000);
480 // in some readers, reset() may throw an exception if
481 // the remaining portion of the input is greater than
482 // the mark size (1,000,000 above).
484 this.index = startIndex;
485 this.character = startCharacter;
486 this.line = startLine;
491 } catch (IOException exception) {
492 throw new JSONException(exception);
499 * Make a JSONException to signal a syntax error.
501 * @param message The error message.
502 * @return A JSONException object, suitable for throwing
504 public JSONException syntaxError(String message) {
505 return new JSONException(message + this.toString());
509 * Make a JSONException to signal a syntax error.
511 * @param message The error message.
512 * @param causedBy The throwable that caused the error.
513 * @return A JSONException object, suitable for throwing
515 public JSONException syntaxError(String message, Throwable causedBy) {
516 return new JSONException(message + this.toString(), causedBy);
520 * Make a printable string of this JSONTokener.
522 * @return " at {index} [character {character} line {line}]"
525 public String toString() {
526 return " at " + this.index + " [character " + this.character + " line " +