4 Copyright (c) 2002 JSON.org
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
16 The Software shall be used for Good, not Evil.
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 import java.io.IOException;
28 import java.io.Writer;
29 import java.lang.reflect.Array;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Iterator;
36 * A JSONArray is an ordered sequence of values. Its external text form is a
37 * string wrapped in square brackets with commas separating the values. The
38 * internal form is an object having <code>get</code> and <code>opt</code>
39 * methods for accessing the values by index, and <code>put</code> methods for
40 * adding or replacing values. The values can be any of these types:
41 * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
42 * <code>Number</code>, <code>String</code>, or the
43 * <code>JSONObject.NULL object</code>.
45 * The constructor can convert a JSON text into a Java object. The
46 * <code>toString</code> method converts to JSON text.
48 * A <code>get</code> method returns a value if one can be found, and throws an
49 * exception if one cannot be found. An <code>opt</code> method returns a
50 * default value instead of throwing an exception, and so is useful for
51 * obtaining optional values.
53 * The generic <code>get()</code> and <code>opt()</code> methods return an
54 * object which you can cast or query for type. There are also typed
55 * <code>get</code> and <code>opt</code> methods that do type checking and type
58 * The texts produced by the <code>toString</code> methods strictly conform to
59 * JSON syntax rules. The constructors are more forgiving in the texts they will
62 * <li>An extra <code>,</code> <small>(comma)</small> may appear just
63 * before the closing bracket.</li>
64 * <li>The <code>null</code> value will be inserted when there
65 * is <code>,</code> <small>(comma)</small> elision.</li>
66 * <li>Strings may be quoted with <code>'</code> <small>(single
67 * quote)</small>.</li>
68 * <li>Strings do not need to be quoted at all if they do not begin with a quote
69 * or single quote, and if they do not contain leading or trailing spaces,
70 * and if they do not contain any of these characters:
71 * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
72 * and if they are not the reserved words <code>true</code>,
73 * <code>false</code>, or <code>null</code>.</li>
74 * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as
75 * well as by <code>,</code> <small>(comma)</small>.</li>
76 * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
77 * <code>0x-</code> <small>(hex)</small> prefix.</li>
78 * <li>Comments written in the slashshlash, slashstar, and hash conventions
79 * will be ignored.</li>
85 public class JSONArray {
89 * The arrayList where the JSONArray's properties are kept.
91 private ArrayList myArrayList;
95 * Construct an empty JSONArray.
98 this.myArrayList = new ArrayList();
102 * Construct a JSONArray from a JSONTokener.
103 * @param x A JSONTokener
104 * @throws JSONException If there is a syntax error.
106 public JSONArray(JSONTokener x) throws JSONException {
108 char c = x.nextClean();
112 } else if (c == '(') {
115 throw x.syntaxError("A JSONArray text must start with '['");
117 if (x.nextClean() == ']') {
122 if (x.nextClean() == ',') {
124 this.myArrayList.add(null);
127 this.myArrayList.add(x.nextValue());
133 if (x.nextClean() == ']') {
141 throw x.syntaxError("Expected a '" + new Character(q) + "'");
145 throw x.syntaxError("Expected a ',' or ']'");
152 * Construct a JSONArray from a source JSON text.
153 * @param source A string that begins with
154 * <code>[</code> <small>(left bracket)</small>
155 * and ends with <code>]</code> <small>(right bracket)</small>.
156 * @throws JSONException If there is a syntax error.
158 public JSONArray(String source) throws JSONException {
159 this(new JSONTokener(source));
164 * Construct a JSONArray from a Collection.
165 * @param collection A Collection.
167 public JSONArray(Collection collection) {
168 this.myArrayList = (collection == null) ?
170 new ArrayList(collection);
174 * Construct a JSONArray from a collection of beans.
175 * The collection should have Java Beans.
177 * @throws JSONException If not an array.
180 public JSONArray(Collection collection,boolean includeSuperClass) {
181 this.myArrayList = new ArrayList();
182 if(collection != null) {
183 for (Iterator iter = collection.iterator(); iter.hasNext();) {
184 this.myArrayList.add(new JSONObject(iter.next(),includeSuperClass));
191 * Construct a JSONArray from an array
192 * @throws JSONException If not an array.
194 public JSONArray(Object array) throws JSONException {
196 if (array.getClass().isArray()) {
197 int length = Array.getLength(array);
198 for (int i = 0; i < length; i += 1) {
199 this.put(Array.get(array, i));
202 throw new JSONException("JSONArray initial value should be a string or collection or array.");
207 * Construct a JSONArray from an array with a bean.
208 * The array should have Java Beans.
210 * @throws JSONException If not an array.
212 public JSONArray(Object array,boolean includeSuperClass) throws JSONException {
214 if (array.getClass().isArray()) {
215 int length = Array.getLength(array);
216 for (int i = 0; i < length; i += 1) {
217 this.put(new JSONObject(Array.get(array, i),includeSuperClass));
220 throw new JSONException("JSONArray initial value should be a string or collection or array.");
227 * Get the object value associated with an index.
229 * The index must be between 0 and length() - 1.
230 * @return An object value.
231 * @throws JSONException If there is no value for the index.
233 public Object get(int index) throws JSONException {
234 Object o = opt(index);
236 throw new JSONException("JSONArray[" + index + "] not found.");
243 * Get the boolean value associated with an index.
244 * The string values "true" and "false" are converted to boolean.
246 * @param index The index must be between 0 and length() - 1.
248 * @throws JSONException If there is no value for the index or if the
249 * value is not convertable to boolean.
251 public boolean getBoolean(int index) throws JSONException {
252 Object o = get(index);
253 if (o.equals(Boolean.FALSE) ||
254 (o instanceof String &&
255 ((String)o).equalsIgnoreCase("false"))) {
257 } else if (o.equals(Boolean.TRUE) ||
258 (o instanceof String &&
259 ((String)o).equalsIgnoreCase("true"))) {
262 throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
267 * Get the double value associated with an index.
269 * @param index The index must be between 0 and length() - 1.
271 * @throws JSONException If the key is not found or if the value cannot
272 * be converted to a number.
274 public double getDouble(int index) throws JSONException {
275 Object o = get(index);
277 return o instanceof Number ?
278 ((Number)o).doubleValue() :
279 Double.valueOf((String)o).doubleValue();
280 } catch (Exception e) {
281 throw new JSONException("JSONArray[" + index +
282 "] is not a number.");
288 * Get the int value associated with an index.
290 * @param index The index must be between 0 and length() - 1.
292 * @throws JSONException If the key is not found or if the value cannot
293 * be converted to a number.
294 * if the value cannot be converted to a number.
296 public int getInt(int index) throws JSONException {
297 Object o = get(index);
298 return o instanceof Number ?
299 ((Number)o).intValue() : (int)getDouble(index);
304 * Get the JSONArray associated with an index.
305 * @param index The index must be between 0 and length() - 1.
306 * @return A JSONArray value.
307 * @throws JSONException If there is no value for the index. or if the
308 * value is not a JSONArray
310 public JSONArray getJSONArray(int index) throws JSONException {
311 Object o = get(index);
312 if (o instanceof JSONArray) {
315 throw new JSONException("JSONArray[" + index +
316 "] is not a JSONArray.");
321 * Get the JSONObject associated with an index.
322 * @param index subscript
323 * @return A JSONObject value.
324 * @throws JSONException If there is no value for the index or if the
325 * value is not a JSONObject
327 public JSONObject getJSONObject(int index) throws JSONException {
328 Object o = get(index);
329 if (o instanceof JSONObject) {
330 return (JSONObject)o;
332 throw new JSONException("JSONArray[" + index +
333 "] is not a JSONObject.");
338 * Get the long value associated with an index.
340 * @param index The index must be between 0 and length() - 1.
342 * @throws JSONException If the key is not found or if the value cannot
343 * be converted to a number.
345 public long getLong(int index) throws JSONException {
346 Object o = get(index);
347 return o instanceof Number ?
348 ((Number)o).longValue() : (long)getDouble(index);
353 * Get the string associated with an index.
354 * @param index The index must be between 0 and length() - 1.
355 * @return A string value.
356 * @throws JSONException If there is no value for the index.
358 public String getString(int index) throws JSONException {
359 return get(index).toString();
364 * Determine if the value is null.
365 * @param index The index must be between 0 and length() - 1.
366 * @return true if the value at the index is null, or if there is no value.
368 public boolean isNull(int index) {
369 return JSONObject.NULL.equals(opt(index));
374 * Make a string from the contents of this JSONArray. The
375 * <code>separator</code> string is inserted between each element.
376 * Warning: This method assumes that the data structure is acyclical.
377 * @param separator A string that will be inserted between the elements.
379 * @throws JSONException If the array contains an invalid number.
381 public String join(String separator) throws JSONException {
383 StringBuffer sb = new StringBuffer();
385 for (int i = 0; i < len; i += 1) {
387 sb.append(separator);
389 sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
391 return sb.toString();
396 * Get the number of elements in the JSONArray, included nulls.
398 * @return The length (or size).
400 public int length() {
401 return this.myArrayList.size();
406 * Get the optional object value associated with an index.
407 * @param index The index must be between 0 and length() - 1.
408 * @return An object value, or null if there is no
409 * object at that index.
411 public Object opt(int index) {
412 return (index < 0 || index >= length()) ?
413 null : this.myArrayList.get(index);
418 * Get the optional boolean value associated with an index.
419 * It returns false if there is no value at that index,
420 * or if the value is not Boolean.TRUE or the String "true".
422 * @param index The index must be between 0 and length() - 1.
425 public boolean optBoolean(int index) {
426 return optBoolean(index, false);
431 * Get the optional boolean value associated with an index.
432 * It returns the defaultValue if there is no value at that index or if
433 * it is not a Boolean or the String "true" or "false" (case insensitive).
435 * @param index The index must be between 0 and length() - 1.
436 * @param defaultValue A boolean default.
439 public boolean optBoolean(int index, boolean defaultValue) {
441 return getBoolean(index);
442 } catch (Exception e) {
449 * Get the optional double value associated with an index.
450 * NaN is returned if there is no value for the index,
451 * or if the value is not a number and cannot be converted to a number.
453 * @param index The index must be between 0 and length() - 1.
456 public double optDouble(int index) {
457 return optDouble(index, Double.NaN);
462 * Get the optional double value associated with an index.
463 * The defaultValue is returned if there is no value for the index,
464 * or if the value is not a number and cannot be converted to a number.
466 * @param index subscript
467 * @param defaultValue The default value.
470 public double optDouble(int index, double defaultValue) {
472 return getDouble(index);
473 } catch (Exception e) {
480 * Get the optional int value associated with an index.
481 * Zero is returned if there is no value for the index,
482 * or if the value is not a number and cannot be converted to a number.
484 * @param index The index must be between 0 and length() - 1.
487 public int optInt(int index) {
488 return optInt(index, 0);
493 * Get the optional int value associated with an index.
494 * The defaultValue is returned if there is no value for the index,
495 * or if the value is not a number and cannot be converted to a number.
496 * @param index The index must be between 0 and length() - 1.
497 * @param defaultValue The default value.
500 public int optInt(int index, int defaultValue) {
502 return getInt(index);
503 } catch (Exception e) {
510 * Get the optional JSONArray associated with an index.
511 * @param index subscript
512 * @return A JSONArray value, or null if the index has no value,
513 * or if the value is not a JSONArray.
515 public JSONArray optJSONArray(int index) {
516 Object o = opt(index);
517 return o instanceof JSONArray ? (JSONArray)o : null;
522 * Get the optional JSONObject associated with an index.
523 * Null is returned if the key is not found, or null if the index has
524 * no value, or if the value is not a JSONObject.
526 * @param index The index must be between 0 and length() - 1.
527 * @return A JSONObject value.
529 public JSONObject optJSONObject(int index) {
530 Object o = opt(index);
531 return o instanceof JSONObject ? (JSONObject)o : null;
536 * Get the optional long value associated with an index.
537 * Zero is returned if there is no value for the index,
538 * or if the value is not a number and cannot be converted to a number.
540 * @param index The index must be between 0 and length() - 1.
543 public long optLong(int index) {
544 return optLong(index, 0);
549 * Get the optional long value associated with an index.
550 * The defaultValue is returned if there is no value for the index,
551 * or if the value is not a number and cannot be converted to a number.
552 * @param index The index must be between 0 and length() - 1.
553 * @param defaultValue The default value.
556 public long optLong(int index, long defaultValue) {
558 return getLong(index);
559 } catch (Exception e) {
566 * Get the optional string value associated with an index. It returns an
567 * empty string if there is no value at that index. If the value
568 * is not a string and is not null, then it is coverted to a string.
570 * @param index The index must be between 0 and length() - 1.
571 * @return A String value.
573 public String optString(int index) {
574 return optString(index, "");
579 * Get the optional string associated with an index.
580 * The defaultValue is returned if the key is not found.
582 * @param index The index must be between 0 and length() - 1.
583 * @param defaultValue The default value.
584 * @return A String value.
586 public String optString(int index, String defaultValue) {
587 Object o = opt(index);
588 return o != null ? o.toString() : defaultValue;
593 * Append a boolean value. This increases the array's length by one.
595 * @param value A boolean value.
598 public JSONArray put(boolean value) {
599 put(value ? Boolean.TRUE : Boolean.FALSE);
605 * Put a value in the JSONArray, where the value will be a
606 * JSONArray which is produced from a Collection.
607 * @param value A Collection value.
610 public JSONArray put(Collection value) {
611 put(new JSONArray(value));
617 * Append a double value. This increases the array's length by one.
619 * @param value A double value.
620 * @throws JSONException if the value is not finite.
623 public JSONArray put(double value) throws JSONException {
624 Double d = new Double(value);
625 JSONObject.testValidity(d);
632 * Append an int value. This increases the array's length by one.
634 * @param value An int value.
637 public JSONArray put(int value) {
638 put(new Integer(value));
644 * Append an long value. This increases the array's length by one.
646 * @param value A long value.
649 public JSONArray put(long value) {
650 put(new Long(value));
656 * Put a value in the JSONArray, where the value will be a
657 * JSONObject which is produced from a Map.
658 * @param value A Map value.
661 public JSONArray put(Map value) {
662 put(new JSONObject(value));
668 * Append an object value. This increases the array's length by one.
669 * @param value An object value. The value should be a
670 * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
671 * JSONObject.NULL object.
674 public JSONArray put(Object value) {
675 this.myArrayList.add(value);
681 * Put or replace a boolean value in the JSONArray. If the index is greater
682 * than the length of the JSONArray, then null elements will be added as
683 * necessary to pad it out.
684 * @param index The subscript.
685 * @param value A boolean value.
687 * @throws JSONException If the index is negative.
689 public JSONArray put(int index, boolean value) throws JSONException {
690 put(index, value ? Boolean.TRUE : Boolean.FALSE);
696 * Put a value in the JSONArray, where the value will be a
697 * JSONArray which is produced from a Collection.
698 * @param index The subscript.
699 * @param value A Collection value.
701 * @throws JSONException If the index is negative or if the value is
704 public JSONArray put(int index, Collection value) throws JSONException {
705 put(index, new JSONArray(value));
711 * Put or replace a double value. If the index is greater than the length of
712 * the JSONArray, then null elements will be added as necessary to pad
714 * @param index The subscript.
715 * @param value A double value.
717 * @throws JSONException If the index is negative or if the value is
720 public JSONArray put(int index, double value) throws JSONException {
721 put(index, new Double(value));
727 * Put or replace an int value. If the index is greater than the length of
728 * the JSONArray, then null elements will be added as necessary to pad
730 * @param index The subscript.
731 * @param value An int value.
733 * @throws JSONException If the index is negative.
735 public JSONArray put(int index, int value) throws JSONException {
736 put(index, new Integer(value));
742 * Put or replace a long value. If the index is greater than the length of
743 * the JSONArray, then null elements will be added as necessary to pad
745 * @param index The subscript.
746 * @param value A long value.
748 * @throws JSONException If the index is negative.
750 public JSONArray put(int index, long value) throws JSONException {
751 put(index, new Long(value));
757 * Put a value in the JSONArray, where the value will be a
758 * JSONObject which is produced from a Map.
759 * @param index The subscript.
760 * @param value The Map value.
762 * @throws JSONException If the index is negative or if the the value is
765 public JSONArray put(int index, Map value) throws JSONException {
766 put(index, new JSONObject(value));
772 * Put or replace an object value in the JSONArray. If the index is greater
773 * than the length of the JSONArray, then null elements will be added as
774 * necessary to pad it out.
775 * @param index The subscript.
776 * @param value The value to put into the array. The value should be a
777 * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
778 * JSONObject.NULL object.
780 * @throws JSONException If the index is negative or if the the value is
783 public JSONArray put(int index, Object value) throws JSONException {
784 JSONObject.testValidity(value);
786 throw new JSONException("JSONArray[" + index + "] not found.");
788 if (index < length()) {
789 this.myArrayList.set(index, value);
791 while (index != length()) {
792 put(JSONObject.NULL);
801 * Produce a JSONObject by combining a JSONArray of names with the values
803 * @param names A JSONArray containing a list of key strings. These will be
804 * paired with the values.
805 * @return A JSONObject, or null if there are no names or if this JSONArray
807 * @throws JSONException If any of the names are null.
809 public JSONObject toJSONObject(JSONArray names) throws JSONException {
810 if (names == null || names.length() == 0 || length() == 0) {
813 JSONObject jo = new JSONObject();
814 for (int i = 0; i < names.length(); i += 1) {
815 jo.put(names.getString(i), this.opt(i));
822 * Make a JSON text of this JSONArray. For compactness, no
823 * unnecessary whitespace is added. If it is not possible to produce a
824 * syntactically correct JSON text then null will be returned instead. This
825 * could occur if the array contains an invalid number.
827 * Warning: This method assumes that the data structure is acyclical.
829 * @return a printable, displayable, transmittable
830 * representation of the array.
832 public String toString() {
834 return '[' + join(",") + ']';
835 } catch (Exception e) {
842 * Make a prettyprinted JSON text of this JSONArray.
843 * Warning: This method assumes that the data structure is acyclical.
844 * @param indentFactor The number of spaces to add to each level of
846 * @return a printable, displayable, transmittable
847 * representation of the object, beginning
848 * with <code>[</code> <small>(left bracket)</small> and ending
849 * with <code>]</code> <small>(right bracket)</small>.
850 * @throws JSONException
852 public String toString(int indentFactor) throws JSONException {
853 return toString(indentFactor, 0);
858 * Make a prettyprinted JSON text of this JSONArray.
859 * Warning: This method assumes that the data structure is acyclical.
860 * @param indentFactor The number of spaces to add to each level of
862 * @param indent The indention of the top level.
863 * @return a printable, displayable, transmittable
864 * representation of the array.
865 * @throws JSONException
867 String toString(int indentFactor, int indent) throws JSONException {
873 StringBuffer sb = new StringBuffer("[");
875 sb.append(JSONObject.valueToString(this.myArrayList.get(0),
876 indentFactor, indent));
878 int newindent = indent + indentFactor;
880 for (i = 0; i < len; i += 1) {
884 for (int j = 0; j < newindent; j += 1) {
887 sb.append(JSONObject.valueToString(this.myArrayList.get(i),
888 indentFactor, newindent));
891 for (i = 0; i < indent; i += 1) {
896 return sb.toString();
901 * Write the contents of the JSONArray as JSON text to a writer.
902 * For compactness, no whitespace is added.
904 * Warning: This method assumes that the data structure is acyclical.
906 * @return The writer.
907 * @throws JSONException
909 public Writer write(Writer writer) throws JSONException {
916 for (int i = 0; i < len; i += 1) {
920 Object v = this.myArrayList.get(i);
921 if (v instanceof JSONObject) {
922 ((JSONObject)v).write(writer);
923 } else if (v instanceof JSONArray) {
924 ((JSONArray)v).write(writer);
926 writer.write(JSONObject.valueToString(v));
932 } catch (IOException e) {
933 throw new JSONException(e);