]> WPIA git - gigi.git/blob - lib/json/org/json/JSONTokener.java
add: import org.json
[gigi.git] / lib / json / org / json / JSONTokener.java
1 package org.json;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.io.Reader;
8 import java.io.StringReader;
9
10 /*
11 Copyright (c) 2002 JSON.org
12
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:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 The Software shall be used for Good, not Evil.
24
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
31 SOFTWARE.
32 */
33
34 /**
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.
38  * @author JSON.org
39  * @version 2014-05-03
40  */
41 public class JSONTokener {
42
43     private long    character;
44     private boolean eof;
45     private long    index;
46     private long    line;
47     private char    previous;
48     private Reader  reader;
49     private boolean usePrevious;
50
51
52     /**
53      * Construct a JSONTokener from a Reader.
54      *
55      * @param reader     A reader.
56      */
57     public JSONTokener(Reader reader) {
58         this.reader = reader.markSupported()
59             ? reader
60             : new BufferedReader(reader);
61         this.eof = false;
62         this.usePrevious = false;
63         this.previous = 0;
64         this.index = 0;
65         this.character = 1;
66         this.line = 1;
67     }
68
69
70     /**
71      * Construct a JSONTokener from an InputStream.
72      * @param inputStream The source.
73      */
74     public JSONTokener(InputStream inputStream) {
75         this(new InputStreamReader(inputStream));
76     }
77
78
79     /**
80      * Construct a JSONTokener from a string.
81      *
82      * @param s     A source string.
83      */
84     public JSONTokener(String s) {
85         this(new StringReader(s));
86     }
87
88
89     /**
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
95      */
96     public void back() throws JSONException {
97         if (this.usePrevious || this.index <= 0) {
98             throw new JSONException("Stepping back two steps is not supported");
99         }
100         this.index -= 1;
101         this.character -= 1;
102         this.usePrevious = true;
103         this.eof = false;
104     }
105
106
107     /**
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.
112      */
113     public static int dehexchar(char c) {
114         if (c >= '0' && c <= '9') {
115             return c - '0';
116         }
117         if (c >= 'A' && c <= 'F') {
118             return c - ('A' - 10);
119         }
120         if (c >= 'a' && c <= 'f') {
121             return c - ('a' - 10);
122         }
123         return -1;
124     }
125
126     /**
127      * @return true if at the end of the file and we didn't step back
128      */
129     public boolean end() {
130         return this.eof && !this.usePrevious;
131     }
132
133
134     /**
135      * Determine if the source string still contains characters that next()
136      * can consume.
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.
140      */
141     public boolean more() throws JSONException {
142         this.next();
143         if (this.end()) {
144             return false;
145         }
146         this.back();
147         return true;
148     }
149
150
151     /**
152      * Get the next character in the source string.
153      *
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.
156      */
157     public char next() throws JSONException {
158         int c;
159         if (this.usePrevious) {
160             this.usePrevious = false;
161             c = this.previous;
162         } else {
163             try {
164                 c = this.reader.read();
165             } catch (IOException exception) {
166                 throw new JSONException(exception);
167             }
168
169             if (c <= 0) { // End of stream
170                 this.eof = true;
171                 c = 0;
172             }
173         }
174         this.index += 1;
175         if (this.previous == '\r') {
176             this.line += 1;
177             this.character = c == '\n' ? 0 : 1;
178         } else if (c == '\n') {
179             this.line += 1;
180             this.character = 0;
181         } else {
182             this.character += 1;
183         }
184         this.previous = (char) c;
185         return this.previous;
186     }
187
188
189     /**
190      * Consume the next character, and check that it matches a specified
191      * character.
192      * @param c The character to match.
193      * @return The character.
194      * @throws JSONException if the character does not match.
195      */
196     public char next(char c) throws JSONException {
197         char n = this.next();
198         if (n != c) {
199             throw this.syntaxError("Expected '" + c + "' and instead saw '" +
200                     n + "'");
201         }
202         return n;
203     }
204
205
206     /**
207      * Get the next n characters.
208      *
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.
214      */
215      public String next(int n) throws JSONException {
216          if (n == 0) {
217              return "";
218          }
219
220          char[] chars = new char[n];
221          int pos = 0;
222
223          while (pos < n) {
224              chars[pos] = this.next();
225              if (this.end()) {
226                  throw this.syntaxError("Substring bounds error");
227              }
228              pos += 1;
229          }
230          return new String(chars);
231      }
232
233
234     /**
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.
238      */
239     public char nextClean() throws JSONException {
240         for (;;) {
241             char c = this.next();
242             if (c == 0 || c > ' ') {
243                 return c;
244             }
245         }
246     }
247
248
249     /**
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
253      * accept them.
254      * @param quote The quoting character, either
255      *      <code>"</code>&nbsp;<small>(double quote)</small> or
256      *      <code>'</code>&nbsp;<small>(single quote)</small>.
257      * @return      A String.
258      * @throws JSONException Unterminated string.
259      */
260     public String nextString(char quote) throws JSONException {
261         char c;
262         StringBuilder sb = new StringBuilder();
263         for (;;) {
264             c = this.next();
265             switch (c) {
266             case 0:
267             case '\n':
268             case '\r':
269                 throw this.syntaxError("Unterminated string");
270             case '\\':
271                 c = this.next();
272                 switch (c) {
273                 case 'b':
274                     sb.append('\b');
275                     break;
276                 case 't':
277                     sb.append('\t');
278                     break;
279                 case 'n':
280                     sb.append('\n');
281                     break;
282                 case 'f':
283                     sb.append('\f');
284                     break;
285                 case 'r':
286                     sb.append('\r');
287                     break;
288                 case 'u':
289                     try {
290                         sb.append((char)Integer.parseInt(this.next(4), 16));
291                     } catch (NumberFormatException e) {
292                         throw this.syntaxError("Illegal escape.", e);
293                     }
294                     break;
295                 case '"':
296                 case '\'':
297                 case '\\':
298                 case '/':
299                     sb.append(c);
300                     break;
301                 default:
302                     throw this.syntaxError("Illegal escape.");
303                 }
304                 break;
305             default:
306                 if (c == quote) {
307                     return sb.toString();
308                 }
309                 sb.append(c);
310             }
311         }
312     }
313
314
315     /**
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.
319      * @return   A string.
320      * @throws JSONException Thrown if there is an error while searching
321      *  for the delimiter
322      */
323     public String nextTo(char delimiter) throws JSONException {
324         StringBuilder sb = new StringBuilder();
325         for (;;) {
326             char c = this.next();
327             if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
328                 if (c != 0) {
329                     this.back();
330                 }
331                 return sb.toString().trim();
332             }
333             sb.append(c);
334         }
335     }
336
337
338     /**
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
344      *  for the delimiter
345      */
346     public String nextTo(String delimiters) throws JSONException {
347         char c;
348         StringBuilder sb = new StringBuilder();
349         for (;;) {
350             c = this.next();
351             if (delimiters.indexOf(c) >= 0 || c == 0 ||
352                     c == '\n' || c == '\r') {
353                 if (c != 0) {
354                     this.back();
355                 }
356                 return sb.toString().trim();
357             }
358             sb.append(c);
359         }
360     }
361
362
363     /**
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.
367      *
368      * @return An object.
369      */
370     public Object nextValue() throws JSONException {
371         char c = this.nextClean();
372         String string;
373
374         switch (c) {
375             case '"':
376             case '\'':
377                 return this.nextString(c);
378             case '{':
379                 this.back();
380                 return new JSONObject(this);
381             case '[':
382                 this.back();
383                 return new JSONArray(this);
384         }
385
386         /*
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.
390          *
391          * Accumulate characters until we reach the end of the text or a
392          * formatting character.
393          */
394
395         StringBuilder sb = new StringBuilder();
396         while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
397             sb.append(c);
398             c = this.next();
399         }
400         this.back();
401
402         string = sb.toString().trim();
403         if ("".equals(string)) {
404             throw this.syntaxError("Missing value");
405         }
406         return JSONObject.stringToValue(string);
407     }
408
409
410     /**
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
415      * is not found.
416      * @throws JSONException Thrown if there is an error while searching
417      *  for the to character
418      */
419     public char skipTo(char to) throws JSONException {
420         char c;
421         try {
422             long startIndex = this.index;
423             long startCharacter = this.character;
424             long startLine = this.line;
425             this.reader.mark(1000000);
426             do {
427                 c = this.next();
428                 if (c == 0) {
429                     this.reader.reset();
430                     this.index = startIndex;
431                     this.character = startCharacter;
432                     this.line = startLine;
433                     return c;
434                 }
435             } while (c != to);
436         } catch (IOException exception) {
437             throw new JSONException(exception);
438         }
439         this.back();
440         return c;
441     }
442
443
444     /**
445      * Make a JSONException to signal a syntax error.
446      *
447      * @param message The error message.
448      * @return  A JSONException object, suitable for throwing
449      */
450     public JSONException syntaxError(String message) {
451         return new JSONException(message + this.toString());
452     }
453
454     /**
455      * Make a JSONException to signal a syntax error.
456      *
457      * @param message The error message.
458      * @param causedBy The throwable that caused the error.
459      * @return  A JSONException object, suitable for throwing
460      */
461     public JSONException syntaxError(String message, Throwable causedBy) {
462         return new JSONException(message + this.toString(), causedBy);
463     }
464
465     /**
466      * Make a printable string of this JSONTokener.
467      *
468      * @return " at {index} [character {character} line {line}]"
469      */
470     @Override
471     public String toString() {
472         return " at " + this.index + " [character " + this.character + " line " +
473             this.line + "]";
474     }
475 }