root/tools/routingservice/branches/wrs-2.0/lib/org/json/JSONArray.java

Revision 305, 30.2 KB (checked in by anton, 19 months ago)

GeoJSON template fixed for catch service

Line 
1package org.json;
2
3/*
4Copyright (c) 2002 JSON.org
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16The Software shall be used for Good, not Evil.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24SOFTWARE.
25*/
26
27import java.io.IOException;
28import java.io.Writer;
29import java.lang.reflect.Array;
30import java.util.ArrayList;
31import java.util.Collection;
32import java.util.Iterator;
33import java.util.Map;
34
35/**
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>.
44 * <p>
45 * The constructor can convert a JSON text into a Java object. The
46 * <code>toString</code> method converts to JSON text.
47 * <p>
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.
52 * <p>
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
56 * coercion for you.
57 * <p>
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
60 * accept:
61 * <ul>
62 * <li>An extra <code>,</code>&nbsp;<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>&nbsp;<small>(comma)</small> elision.</li>
66 * <li>Strings may be quoted with <code>'</code>&nbsp;<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 * </ul>
79
80 * @author JSON.org
81 * @version 2008-02-09
82 */
83public class JSONArray {
84
85
86    /**
87     * The arrayList where the JSONArray's properties are kept.
88     */
89    private ArrayList myArrayList;
90
91
92    /**
93     * Construct an empty JSONArray.
94     */
95    public JSONArray() {
96        this.myArrayList = new ArrayList();
97    }
98
99    /**
100     * Construct a JSONArray from a JSONTokener.
101     * @param x A JSONTokener
102     * @throws JSONException If there is a syntax error.
103     */
104    public JSONArray(JSONTokener x) throws JSONException {
105        this();
106        char c = x.nextClean();
107        char q;
108        if (c == '[') {
109            q = ']';
110        } else if (c == '(') {
111            q = ')';
112        } else {
113            throw x.syntaxError("A JSONArray text must start with '['");
114        }
115        if (x.nextClean() == ']') {
116            return;
117        }
118        x.back();
119        for (;;) {
120            if (x.nextClean() == ',') {
121                x.back();
122                this.myArrayList.add(null);
123            } else {
124                x.back();
125                this.myArrayList.add(x.nextValue());
126            }
127            c = x.nextClean();
128            switch (c) {
129            case ';':
130            case ',':
131                if (x.nextClean() == ']') {
132                    return;
133                }
134                x.back();
135                break;
136            case ']':
137            case ')':
138                if (q != c) {
139                    throw x.syntaxError("Expected a '" + new Character(q) + "'");
140                }
141                return;
142            default:
143                throw x.syntaxError("Expected a ',' or ']'");
144            }
145        }
146    }
147
148
149    /**
150     * Construct a JSONArray from a source JSON text.
151     * @param source     A string that begins with
152     * <code>[</code>&nbsp;<small>(left bracket)</small>
153     *  and ends with <code>]</code>&nbsp;<small>(right bracket)</small>.
154     *  @throws JSONException If there is a syntax error.
155     */
156    public JSONArray(String source) throws JSONException {
157        this(new JSONTokener(source));
158    }
159
160
161    /**
162     * Construct a JSONArray from a Collection.
163     * @param collection     A Collection.
164     */
165    public JSONArray(Collection collection) {
166        this.myArrayList = (collection == null) ?
167            new ArrayList() :
168            new ArrayList(collection);
169    }
170
171    /**
172     * Construct a JSONArray from a collection of beans.
173     * The collection should have Java Beans.
174     *
175     * @throws JSONException If not an array.
176     */
177
178    public JSONArray(Collection collection, boolean includeSuperClass) {
179                this.myArrayList = new ArrayList();
180                if (collection != null) {
181                        Iterator iter = collection.iterator();;
182                        while (iter.hasNext()) {
183                            Object o = iter.next();
184                            if (o instanceof Map || !JSONObject.isStandardProperty(o.getClass())) {
185                                this.myArrayList.add(new JSONObject((Map)o, includeSuperClass));
186                            } else {
187                    this.myArrayList.add(o); 
188                                }
189                        }
190                }
191    }
192
193   
194    /**
195     * Construct a JSONArray from an array
196     * @throws JSONException If not an array.
197     */
198    public JSONArray(Object array) throws JSONException {
199        this();
200        if (array.getClass().isArray()) {
201            int length = Array.getLength(array);
202            for (int i = 0; i < length; i += 1) {
203                this.put(Array.get(array, i));
204            }
205        } else {
206            throw new JSONException("JSONArray initial value should be a string or collection or array.");
207        }
208    }
209
210    /**
211     * Construct a JSONArray from an array with a bean.
212     * The array should have Java Beans.
213     *
214     * @throws JSONException If not an array.
215     */
216    public JSONArray(Object array,boolean includeSuperClass) throws JSONException {
217        this();
218        if (array.getClass().isArray()) {
219            int length = Array.getLength(array);
220            for (int i = 0; i < length; i += 1) {
221                Object o = Array.get(array, i);
222                if (JSONObject.isStandardProperty(o.getClass())) {
223                    this.myArrayList.add(o); 
224                } else {
225                    this.myArrayList.add(new JSONObject(o,includeSuperClass)); 
226                }
227            }
228        } else {
229            throw new JSONException("JSONArray initial value should be a string or collection or array.");
230        }
231    }
232
233   
234   
235    /**
236     * Get the object value associated with an index.
237     * @param index
238     *  The index must be between 0 and length() - 1.
239     * @return An object value.
240     * @throws JSONException If there is no value for the index.
241     */
242    public Object get(int index) throws JSONException {
243        Object o = opt(index);
244        if (o == null) {
245            throw new JSONException("JSONArray[" + index + "] not found.");
246        }
247        return o;
248    }
249
250
251    /**
252     * Get the boolean value associated with an index.
253     * The string values "true" and "false" are converted to boolean.
254     *
255     * @param index The index must be between 0 and length() - 1.
256     * @return      The truth.
257     * @throws JSONException If there is no value for the index or if the
258     *  value is not convertable to boolean.
259     */
260    public boolean getBoolean(int index) throws JSONException {
261        Object o = get(index);
262        if (o.equals(Boolean.FALSE) ||
263                (o instanceof String &&
264                ((String)o).equalsIgnoreCase("false"))) {
265            return false;
266        } else if (o.equals(Boolean.TRUE) ||
267                (o instanceof String &&
268                ((String)o).equalsIgnoreCase("true"))) {
269            return true;
270        }
271        throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
272    }
273
274
275    /**
276     * Get the double value associated with an index.
277     *
278     * @param index The index must be between 0 and length() - 1.
279     * @return      The value.
280     * @throws   JSONException If the key is not found or if the value cannot
281     *  be converted to a number.
282     */
283    public double getDouble(int index) throws JSONException {
284        Object o = get(index);
285        try {
286            return o instanceof Number ?
287                ((Number)o).doubleValue() :
288                Double.valueOf((String)o).doubleValue();
289        } catch (Exception e) {
290            throw new JSONException("JSONArray[" + index +
291                "] is not a number.");
292        }
293    }
294
295
296    /**
297     * Get the int value associated with an index.
298     *
299     * @param index The index must be between 0 and length() - 1.
300     * @return      The value.
301     * @throws   JSONException If the key is not found or if the value cannot
302     *  be converted to a number.
303     *  if the value cannot be converted to a number.
304     */
305    public int getInt(int index) throws JSONException {
306        Object o = get(index);
307        return o instanceof Number ?
308                ((Number)o).intValue() : (int)getDouble(index);
309    }
310
311
312    /**
313     * Get the JSONArray associated with an index.
314     * @param index The index must be between 0 and length() - 1.
315     * @return      A JSONArray value.
316     * @throws JSONException If there is no value for the index. or if the
317     * value is not a JSONArray
318     */
319    public JSONArray getJSONArray(int index) throws JSONException {
320        Object o = get(index);
321        if (o instanceof JSONArray) {
322            return (JSONArray)o;
323        }
324        throw new JSONException("JSONArray[" + index +
325                "] is not a JSONArray.");
326    }
327
328
329    /**
330     * Get the JSONObject associated with an index.
331     * @param index subscript
332     * @return      A JSONObject value.
333     * @throws JSONException If there is no value for the index or if the
334     * value is not a JSONObject
335     */
336    public JSONObject getJSONObject(int index) throws JSONException {
337        Object o = get(index);
338        if (o instanceof JSONObject) {
339            return (JSONObject)o;
340        }
341        throw new JSONException("JSONArray[" + index +
342            "] is not a JSONObject.");
343    }
344
345
346    /**
347     * Get the long value associated with an index.
348     *
349     * @param index The index must be between 0 and length() - 1.
350     * @return      The value.
351     * @throws   JSONException If the key is not found or if the value cannot
352     *  be converted to a number.
353     */
354    public long getLong(int index) throws JSONException {
355        Object o = get(index);
356        return o instanceof Number ?
357                ((Number)o).longValue() : (long)getDouble(index);
358    }
359
360
361    /**
362     * Get the string associated with an index.
363     * @param index The index must be between 0 and length() - 1.
364     * @return      A string value.
365     * @throws JSONException If there is no value for the index.
366     */
367    public String getString(int index) throws JSONException {
368        return get(index).toString();
369    }
370
371
372    /**
373     * Determine if the value is null.
374     * @param index The index must be between 0 and length() - 1.
375     * @return true if the value at the index is null, or if there is no value.
376     */
377    public boolean isNull(int index) {
378        return JSONObject.NULL.equals(opt(index));
379    }
380
381
382    /**
383     * Make a string from the contents of this JSONArray. The
384     * <code>separator</code> string is inserted between each element.
385     * Warning: This method assumes that the data structure is acyclical.
386     * @param separator A string that will be inserted between the elements.
387     * @return a string.
388     * @throws JSONException If the array contains an invalid number.
389     */
390    public String join(String separator) throws JSONException {
391        int len = length();
392        StringBuffer sb = new StringBuffer();
393
394        for (int i = 0; i < len; i += 1) {
395            if (i > 0) {
396                sb.append(separator);
397            }
398            sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
399        }
400        return sb.toString();
401    }
402
403
404    /**
405     * Get the number of elements in the JSONArray, included nulls.
406     *
407     * @return The length (or size).
408     */
409    public int length() {
410        return this.myArrayList.size();
411    }
412
413
414    /**
415     * Get the optional object value associated with an index.
416     * @param index The index must be between 0 and length() - 1.
417     * @return      An object value, or null if there is no
418     *              object at that index.
419     */
420    public Object opt(int index) {
421        return (index < 0 || index >= length()) ?
422            null : this.myArrayList.get(index);
423    }
424
425
426    /**
427     * Get the optional boolean value associated with an index.
428     * It returns false if there is no value at that index,
429     * or if the value is not Boolean.TRUE or the String "true".
430     *
431     * @param index The index must be between 0 and length() - 1.
432     * @return      The truth.
433     */
434    public boolean optBoolean(int index)  {
435        return optBoolean(index, false);
436    }
437
438
439    /**
440     * Get the optional boolean value associated with an index.
441     * It returns the defaultValue if there is no value at that index or if
442     * it is not a Boolean or the String "true" or "false" (case insensitive).
443     *
444     * @param index The index must be between 0 and length() - 1.
445     * @param defaultValue     A boolean default.
446     * @return      The truth.
447     */
448    public boolean optBoolean(int index, boolean defaultValue)  {
449        try {
450            return getBoolean(index);
451        } catch (Exception e) {
452            return defaultValue;
453        }
454    }
455
456
457    /**
458     * Get the optional double value associated with an index.
459     * NaN is returned if there is no value for the index,
460     * or if the value is not a number and cannot be converted to a number.
461     *
462     * @param index The index must be between 0 and length() - 1.
463     * @return      The value.
464     */
465    public double optDouble(int index) {
466        return optDouble(index, Double.NaN);
467    }
468
469
470    /**
471     * Get the optional double value associated with an index.
472     * The defaultValue is returned if there is no value for the index,
473     * or if the value is not a number and cannot be converted to a number.
474     *
475     * @param index subscript
476     * @param defaultValue     The default value.
477     * @return      The value.
478     */
479    public double optDouble(int index, double defaultValue) {
480        try {
481            return getDouble(index);
482        } catch (Exception e) {
483            return defaultValue;
484        }
485    }
486
487
488    /**
489     * Get the optional int value associated with an index.
490     * Zero is returned if there is no value for the index,
491     * or if the value is not a number and cannot be converted to a number.
492     *
493     * @param index The index must be between 0 and length() - 1.
494     * @return      The value.
495     */
496    public int optInt(int index) {
497        return optInt(index, 0);
498    }
499
500
501    /**
502     * Get the optional int value associated with an index.
503     * The defaultValue is returned if there is no value for the index,
504     * or if the value is not a number and cannot be converted to a number.
505     * @param index The index must be between 0 and length() - 1.
506     * @param defaultValue     The default value.
507     * @return      The value.
508     */
509    public int optInt(int index, int defaultValue) {
510        try {
511            return getInt(index);
512        } catch (Exception e) {
513            return defaultValue;
514        }
515    }
516
517
518    /**
519     * Get the optional JSONArray associated with an index.
520     * @param index subscript
521     * @return      A JSONArray value, or null if the index has no value,
522     * or if the value is not a JSONArray.
523     */
524    public JSONArray optJSONArray(int index) {
525        Object o = opt(index);
526        return o instanceof JSONArray ? (JSONArray)o : null;
527    }
528
529
530    /**
531     * Get the optional JSONObject associated with an index.
532     * Null is returned if the key is not found, or null if the index has
533     * no value, or if the value is not a JSONObject.
534     *
535     * @param index The index must be between 0 and length() - 1.
536     * @return      A JSONObject value.
537     */
538    public JSONObject optJSONObject(int index) {
539        Object o = opt(index);
540        return o instanceof JSONObject ? (JSONObject)o : null;
541    }
542
543
544    /**
545     * Get the optional long value associated with an index.
546     * Zero is returned if there is no value for the index,
547     * or if the value is not a number and cannot be converted to a number.
548     *
549     * @param index The index must be between 0 and length() - 1.
550     * @return      The value.
551     */
552    public long optLong(int index) {
553        return optLong(index, 0);
554    }
555
556
557    /**
558     * Get the optional long value associated with an index.
559     * The defaultValue is returned if there is no value for the index,
560     * or if the value is not a number and cannot be converted to a number.
561     * @param index The index must be between 0 and length() - 1.
562     * @param defaultValue     The default value.
563     * @return      The value.
564     */
565    public long optLong(int index, long defaultValue) {
566        try {
567            return getLong(index);
568        } catch (Exception e) {
569            return defaultValue;
570        }
571    }
572
573
574    /**
575     * Get the optional string value associated with an index. It returns an
576     * empty string if there is no value at that index. If the value
577     * is not a string and is not null, then it is coverted to a string.
578     *
579     * @param index The index must be between 0 and length() - 1.
580     * @return      A String value.
581     */
582    public String optString(int index) {
583        return optString(index, "");
584    }
585
586
587    /**
588     * Get the optional string associated with an index.
589     * The defaultValue is returned if the key is not found.
590     *
591     * @param index The index must be between 0 and length() - 1.
592     * @param defaultValue     The default value.
593     * @return      A String value.
594     */
595    public String optString(int index, String defaultValue) {
596        Object o = opt(index);
597        return o != null ? o.toString() : defaultValue;
598    }
599
600
601    /**
602     * Append a boolean value. This increases the array's length by one.
603     *
604     * @param value A boolean value.
605     * @return this.
606     */
607    public JSONArray put(boolean value) {
608        put(value ? Boolean.TRUE : Boolean.FALSE);
609        return this;
610    }
611
612
613    /**
614     * Put a value in the JSONArray, where the value will be a
615     * JSONArray which is produced from a Collection.
616     * @param value A Collection value.
617     * @return      this.
618     */
619    public JSONArray put(Collection value) {
620        put(new JSONArray(value));
621        return this;
622    }
623
624
625    /**
626     * Append a double value. This increases the array's length by one.
627     *
628     * @param value A double value.
629     * @throws JSONException if the value is not finite.
630     * @return this.
631     */
632    public JSONArray put(double value) throws JSONException {
633        Double d = new Double(value);
634        JSONObject.testValidity(d);
635        put(d);
636        return this;
637    }
638
639
640    /**
641     * Append an int value. This increases the array's length by one.
642     *
643     * @param value An int value.
644     * @return this.
645     */
646    public JSONArray put(int value) {
647        put(new Integer(value));
648        return this;
649    }
650
651
652    /**
653     * Append an long value. This increases the array's length by one.
654     *
655     * @param value A long value.
656     * @return this.
657     */
658    public JSONArray put(long value) {
659        put(new Long(value));
660        return this;
661    }
662
663
664    /**
665     * Put a value in the JSONArray, where the value will be a
666     * JSONObject which is produced from a Map.
667     * @param value A Map value.
668     * @return      this.
669     */
670    public JSONArray put(Map value) {
671        put(new JSONObject(value));
672        return this;
673    }
674
675
676    /**
677     * Append an object value. This increases the array's length by one.
678     * @param value An object value.  The value should be a
679     *  Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
680     *  JSONObject.NULL object.
681     * @return this.
682     */
683    public JSONArray put(Object value) {
684        this.myArrayList.add(value);
685        return this;
686    }
687
688
689    /**
690     * Put or replace a boolean value in the JSONArray. If the index is greater
691     * than the length of the JSONArray, then null elements will be added as
692     * necessary to pad it out.
693     * @param index The subscript.
694     * @param value A boolean value.
695     * @return this.
696     * @throws JSONException If the index is negative.
697     */
698    public JSONArray put(int index, boolean value) throws JSONException {
699        put(index, value ? Boolean.TRUE : Boolean.FALSE);
700        return this;
701    }
702
703
704    /**
705     * Put a value in the JSONArray, where the value will be a
706     * JSONArray which is produced from a Collection.
707     * @param index The subscript.
708     * @param value A Collection value.
709     * @return      this.
710     * @throws JSONException If the index is negative or if the value is
711     * not finite.
712     */
713    public JSONArray put(int index, Collection value) throws JSONException {
714        put(index, new JSONArray(value));
715        return this;
716    }
717
718
719    /**
720     * Put or replace a double value. If the index is greater than the length of
721     *  the JSONArray, then null elements will be added as necessary to pad
722     *  it out.
723     * @param index The subscript.
724     * @param value A double value.
725     * @return this.
726     * @throws JSONException If the index is negative or if the value is
727     * not finite.
728     */
729    public JSONArray put(int index, double value) throws JSONException {
730        put(index, new Double(value));
731        return this;
732    }
733
734
735    /**
736     * Put or replace an int value. If the index is greater than the length of
737     *  the JSONArray, then null elements will be added as necessary to pad
738     *  it out.
739     * @param index The subscript.
740     * @param value An int value.
741     * @return this.
742     * @throws JSONException If the index is negative.
743     */
744    public JSONArray put(int index, int value) throws JSONException {
745        put(index, new Integer(value));
746        return this;
747    }
748
749
750    /**
751     * Put or replace a long value. If the index is greater than the length of
752     *  the JSONArray, then null elements will be added as necessary to pad
753     *  it out.
754     * @param index The subscript.
755     * @param value A long value.
756     * @return this.
757     * @throws JSONException If the index is negative.
758     */
759    public JSONArray put(int index, long value) throws JSONException {
760        put(index, new Long(value));
761        return this;
762    }
763
764
765    /**
766     * Put a value in the JSONArray, where the value will be a
767     * JSONObject which is produced from a Map.
768     * @param index The subscript.
769     * @param value The Map value.
770     * @return      this.
771     * @throws JSONException If the index is negative or if the the value is
772     *  an invalid number.
773     */
774    public JSONArray put(int index, Map value) throws JSONException {
775        put(index, new JSONObject(value));
776        return this;
777    }
778
779
780    /**
781     * Put or replace an object value in the JSONArray. If the index is greater
782     *  than the length of the JSONArray, then null elements will be added as
783     *  necessary to pad it out.
784     * @param index The subscript.
785     * @param value The value to put into the array. The value should be a
786     *  Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
787     *  JSONObject.NULL object.
788     * @return this.
789     * @throws JSONException If the index is negative or if the the value is
790     *  an invalid number.
791     */
792    public JSONArray put(int index, Object value) throws JSONException {
793        JSONObject.testValidity(value);
794        if (index < 0) {
795            throw new JSONException("JSONArray[" + index + "] not found.");
796        }
797        if (index < length()) {
798            this.myArrayList.set(index, value);
799        } else {
800            while (index != length()) {
801                put(JSONObject.NULL);
802            }
803            put(value);
804        }
805        return this;
806    }
807   
808   
809    /**
810     * Remove a index and close the hole.
811     * @param index The index of the element to be removed.
812     * @return The value that was associated with the index,
813     * or null if there was no value.
814     */
815    public Object remove(int index) {
816        Object o = opt(index);
817        this.myArrayList.remove(index);
818        return o;
819    }
820
821
822    /**
823     * Produce a JSONObject by combining a JSONArray of names with the values
824     * of this JSONArray.
825     * @param names A JSONArray containing a list of key strings. These will be
826     * paired with the values.
827     * @return A JSONObject, or null if there are no names or if this JSONArray
828     * has no values.
829     * @throws JSONException If any of the names are null.
830     */
831    public JSONObject toJSONObject(JSONArray names) throws JSONException {
832        if (names == null || names.length() == 0 || length() == 0) {
833            return null;
834        }
835        JSONObject jo = new JSONObject();
836        for (int i = 0; i < names.length(); i += 1) {
837            jo.put(names.getString(i), this.opt(i));
838        }
839        return jo;
840    }
841
842
843    /**
844     * Make a JSON text of this JSONArray. For compactness, no
845     * unnecessary whitespace is added. If it is not possible to produce a
846     * syntactically correct JSON text then null will be returned instead. This
847     * could occur if the array contains an invalid number.
848     * <p>
849     * Warning: This method assumes that the data structure is acyclical.
850     *
851     * @return a printable, displayable, transmittable
852     *  representation of the array.
853     */
854    public String toString() {
855        try {
856            return '[' + join(",") + ']';
857        } catch (Exception e) {
858            return null;
859        }
860    }
861
862
863    /**
864     * Make a prettyprinted JSON text of this JSONArray.
865     * Warning: This method assumes that the data structure is acyclical.
866     * @param indentFactor The number of spaces to add to each level of
867     *  indentation.
868     * @return a printable, displayable, transmittable
869     *  representation of the object, beginning
870     *  with <code>[</code>&nbsp;<small>(left bracket)</small> and ending
871     *  with <code>]</code>&nbsp;<small>(right bracket)</small>.
872     * @throws JSONException
873     */
874    public String toString(int indentFactor) throws JSONException {
875        return toString(indentFactor, 0);
876    }
877
878
879    /**
880     * Make a prettyprinted JSON text of this JSONArray.
881     * Warning: This method assumes that the data structure is acyclical.
882     * @param indentFactor The number of spaces to add to each level of
883     *  indentation.
884     * @param indent The indention of the top level.
885     * @return a printable, displayable, transmittable
886     *  representation of the array.
887     * @throws JSONException
888     */
889    String toString(int indentFactor, int indent) throws JSONException {
890        int len = length();
891        if (len == 0) {
892            return "[]";
893        }
894        int i;
895        StringBuffer sb = new StringBuffer("[");
896        if (len == 1) {
897            sb.append(JSONObject.valueToString(this.myArrayList.get(0),
898                    indentFactor, indent));
899        } else {
900            int newindent = indent + indentFactor;
901            sb.append('\n');
902            for (i = 0; i < len; i += 1) {
903                if (i > 0) {
904                    sb.append(",\n");
905                }
906                for (int j = 0; j < newindent; j += 1) {
907                    sb.append(' ');
908                }
909                sb.append(JSONObject.valueToString(this.myArrayList.get(i),
910                        indentFactor, newindent));
911            }
912            sb.append('\n');
913            for (i = 0; i < indent; i += 1) {
914                sb.append(' ');
915            }
916        }
917        sb.append(']');
918        return sb.toString();
919    }
920
921
922    /**
923     * Write the contents of the JSONArray as JSON text to a writer.
924     * For compactness, no whitespace is added.
925     * <p>
926     * Warning: This method assumes that the data structure is acyclical.
927     *
928     * @return The writer.
929     * @throws JSONException
930     */
931    public Writer write(Writer writer) throws JSONException {
932        try {
933            boolean b = false;
934            int     len = length();
935
936            writer.write('[');
937
938            for (int i = 0; i < len; i += 1) {
939                if (b) {
940                    writer.write(',');
941                }
942                Object v = this.myArrayList.get(i);
943                if (v instanceof JSONObject) {
944                    ((JSONObject)v).write(writer);
945                } else if (v instanceof JSONArray) {
946                    ((JSONArray)v).write(writer);
947                } else {
948                    writer.write(JSONObject.valueToString(v));
949                }
950                b = true;
951            }
952            writer.write(']');
953            return writer;
954        } catch (IOException e) {
955           throw new JSONException(e);
956        }
957    }
958}
Note: See TracBrowser for help on using the browser.