Home » apache-tomcat-6.0.26-src » org.apache » tomcat » util » json » [javadoc | source]

    1   package org.apache.tomcat.util.json;
    2   
    3   /*
    4   Copyright (c) 2002 JSON.org
    5   
    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:
   12   
   13   The above copyright notice and this permission notice shall be included in all
   14   copies or substantial portions of the Software.
   15   
   16   The Software shall be used for Good, not Evil.
   17   
   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
   24   SOFTWARE.
   25   */
   26   
   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;
   33   import 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    * coersion 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    * <li>Comments written in the slashshlash, slashstar, and hash conventions
   79    *     will be ignored.</li>
   80    * </ul>
   81   
   82    * @author JSON.org
   83    * @version 2008-09-18
   84    */
   85   public class JSONArray {
   86   
   87   
   88       /**
   89        * The arrayList where the JSONArray's properties are kept.
   90        */
   91       private ArrayList myArrayList;
   92   
   93   
   94       /**
   95        * Construct an empty JSONArray.
   96        */
   97       public JSONArray() {
   98           this.myArrayList = new ArrayList();
   99       }
  100   
  101       /**
  102        * Construct a JSONArray from a JSONTokener.
  103        * @param x A JSONTokener
  104        * @throws JSONException If there is a syntax error.
  105        */
  106       public JSONArray(JSONTokener x) throws JSONException {
  107           this();
  108           char c = x.nextClean();
  109           char q;
  110           if (c == '[') {
  111               q = ']';
  112           } else if (c == '(') {
  113               q = ')';
  114           } else {
  115               throw x.syntaxError("A JSONArray text must start with '['");
  116           }
  117           if (x.nextClean() == ']') {
  118               return;
  119           }
  120           x.back();
  121           for (;;) {
  122               if (x.nextClean() == ',') {
  123                   x.back();
  124                   this.myArrayList.add(null);
  125               } else {
  126                   x.back();
  127                   this.myArrayList.add(x.nextValue());
  128               }
  129               c = x.nextClean();
  130               switch (c) {
  131               case ';':
  132               case ',':
  133                   if (x.nextClean() == ']') {
  134                       return;
  135                   }
  136                   x.back();
  137                   break;
  138               case ']':
  139               case ')':
  140                   if (q != c) {
  141                       throw x.syntaxError("Expected a '" + new Character(q) + "'");
  142                   }
  143                   return;
  144               default:
  145                   throw x.syntaxError("Expected a ',' or ']'");
  146               }
  147           }
  148       }
  149   
  150   
  151       /**
  152        * Construct a JSONArray from a source JSON text.
  153        * @param source     A string that begins with
  154        * <code>[</code>&nbsp;<small>(left bracket)</small>
  155        *  and ends with <code>]</code>&nbsp;<small>(right bracket)</small>.
  156        *  @throws JSONException If there is a syntax error.
  157        */
  158       public JSONArray(String source) throws JSONException {
  159           this(new JSONTokener(source));
  160       }
  161   
  162   
  163       /**
  164        * Construct a JSONArray from a Collection.
  165        * @param collection     A Collection.
  166        */
  167       public JSONArray(Collection collection) {
  168           this.myArrayList = (collection == null) ?
  169               new ArrayList() :
  170               new ArrayList(collection);
  171       }
  172   
  173       /**
  174        * Construct a JSONArray from a collection of beans.
  175        * The collection should have Java Beans.
  176        * 
  177        * @throws JSONException If not an array.
  178        */
  179   
  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));	
  185   			}
  186   		}
  187       }
  188   
  189       
  190       /**
  191        * Construct a JSONArray from an array
  192        * @throws JSONException If not an array.
  193        */
  194       public JSONArray(Object array) throws JSONException {
  195           this();
  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));
  200               }
  201           } else {
  202               throw new JSONException("JSONArray initial value should be a string or collection or array.");
  203           }
  204       }
  205   
  206       /**
  207        * Construct a JSONArray from an array with a bean.
  208        * The array should have Java Beans.
  209        * 
  210        * @throws JSONException If not an array.
  211        */
  212       public JSONArray(Object array,boolean includeSuperClass) throws JSONException {
  213           this();
  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));
  218               }
  219           } else {
  220               throw new JSONException("JSONArray initial value should be a string or collection or array.");
  221           }
  222       }
  223   
  224       
  225       
  226       /**
  227        * Get the object value associated with an index.
  228        * @param 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.
  232        */
  233       public Object get(int index) throws JSONException {
  234           Object o = opt(index);
  235           if (o == null) {
  236               throw new JSONException("JSONArray[" + index + "] not found.");
  237           }
  238           return o;
  239       }
  240   
  241   
  242       /**
  243        * Get the boolean value associated with an index.
  244        * The string values "true" and "false" are converted to boolean.
  245        *
  246        * @param index The index must be between 0 and length() - 1.
  247        * @return      The truth.
  248        * @throws JSONException If there is no value for the index or if the
  249        *  value is not convertable to boolean.
  250        */
  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"))) {
  256               return false;
  257           } else if (o.equals(Boolean.TRUE) ||
  258                   (o instanceof String &&
  259                   ((String)o).equalsIgnoreCase("true"))) {
  260               return true;
  261           }
  262           throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
  263       }
  264   
  265   
  266       /**
  267        * Get the double value associated with an index.
  268        *
  269        * @param index The index must be between 0 and length() - 1.
  270        * @return      The value.
  271        * @throws   JSONException If the key is not found or if the value cannot
  272        *  be converted to a number.
  273        */
  274       public double getDouble(int index) throws JSONException {
  275           Object o = get(index);
  276           try {
  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.");
  283           }
  284       }
  285   
  286   
  287       /**
  288        * Get the int value associated with an index.
  289        *
  290        * @param index The index must be between 0 and length() - 1.
  291        * @return      The value.
  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.
  295        */
  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);
  300       }
  301   
  302   
  303       /**
  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
  309        */
  310       public JSONArray getJSONArray(int index) throws JSONException {
  311           Object o = get(index);
  312           if (o instanceof JSONArray) {
  313               return (JSONArray)o;
  314           }
  315           throw new JSONException("JSONArray[" + index +
  316                   "] is not a JSONArray.");
  317       }
  318   
  319   
  320       /**
  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
  326        */
  327       public JSONObject getJSONObject(int index) throws JSONException {
  328           Object o = get(index);
  329           if (o instanceof JSONObject) {
  330               return (JSONObject)o;
  331           }
  332           throw new JSONException("JSONArray[" + index +
  333               "] is not a JSONObject.");
  334       }
  335   
  336   
  337       /**
  338        * Get the long value associated with an index.
  339        *
  340        * @param index The index must be between 0 and length() - 1.
  341        * @return      The value.
  342        * @throws   JSONException If the key is not found or if the value cannot
  343        *  be converted to a number.
  344        */
  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);
  349       }
  350   
  351   
  352       /**
  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.
  357        */
  358       public String getString(int index) throws JSONException {
  359           return get(index).toString();
  360       }
  361   
  362   
  363       /**
  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.
  367        */
  368       public boolean isNull(int index) {
  369           return JSONObject.NULL.equals(opt(index));
  370       }
  371   
  372   
  373       /**
  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.
  378        * @return a string.
  379        * @throws JSONException If the array contains an invalid number.
  380        */
  381       public String join(String separator) throws JSONException {
  382           int len = length();
  383           StringBuffer sb = new StringBuffer();
  384   
  385           for (int i = 0; i < len; i += 1) {
  386               if (i > 0) {
  387                   sb.append(separator);
  388               }
  389               sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
  390           }
  391           return sb.toString();
  392       }
  393   
  394   
  395       /**
  396        * Get the number of elements in the JSONArray, included nulls.
  397        *
  398        * @return The length (or size).
  399        */
  400       public int length() {
  401           return this.myArrayList.size();
  402       }
  403   
  404   
  405       /**
  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.
  410        */
  411       public Object opt(int index) {
  412           return (index < 0 || index >= length()) ?
  413               null : this.myArrayList.get(index);
  414       }
  415   
  416   
  417       /**
  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".
  421        *
  422        * @param index The index must be between 0 and length() - 1.
  423        * @return      The truth.
  424        */
  425       public boolean optBoolean(int index)  {
  426           return optBoolean(index, false);
  427       }
  428   
  429   
  430       /**
  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).
  434        *
  435        * @param index The index must be between 0 and length() - 1.
  436        * @param defaultValue     A boolean default.
  437        * @return      The truth.
  438        */
  439       public boolean optBoolean(int index, boolean defaultValue)  {
  440           try {
  441               return getBoolean(index);
  442           } catch (Exception e) {
  443               return defaultValue;
  444           }
  445       }
  446   
  447   
  448       /**
  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.
  452        *
  453        * @param index The index must be between 0 and length() - 1.
  454        * @return      The value.
  455        */
  456       public double optDouble(int index) {
  457           return optDouble(index, Double.NaN);
  458       }
  459   
  460   
  461       /**
  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.
  465        *
  466        * @param index subscript
  467        * @param defaultValue     The default value.
  468        * @return      The value.
  469        */
  470       public double optDouble(int index, double defaultValue) {
  471           try {
  472               return getDouble(index);
  473           } catch (Exception e) {
  474               return defaultValue;
  475           }
  476       }
  477   
  478   
  479       /**
  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.
  483        *
  484        * @param index The index must be between 0 and length() - 1.
  485        * @return      The value.
  486        */
  487       public int optInt(int index) {
  488           return optInt(index, 0);
  489       }
  490   
  491   
  492       /**
  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.
  498        * @return      The value.
  499        */
  500       public int optInt(int index, int defaultValue) {
  501           try {
  502               return getInt(index);
  503           } catch (Exception e) {
  504               return defaultValue;
  505           }
  506       }
  507   
  508   
  509       /**
  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.
  514        */
  515       public JSONArray optJSONArray(int index) {
  516           Object o = opt(index);
  517           return o instanceof JSONArray ? (JSONArray)o : null;
  518       }
  519   
  520   
  521       /**
  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.
  525        *
  526        * @param index The index must be between 0 and length() - 1.
  527        * @return      A JSONObject value.
  528        */
  529       public JSONObject optJSONObject(int index) {
  530           Object o = opt(index);
  531           return o instanceof JSONObject ? (JSONObject)o : null;
  532       }
  533   
  534   
  535       /**
  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.
  539        *
  540        * @param index The index must be between 0 and length() - 1.
  541        * @return      The value.
  542        */
  543       public long optLong(int index) {
  544           return optLong(index, 0);
  545       }
  546   
  547   
  548       /**
  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.
  554        * @return      The value.
  555        */
  556       public long optLong(int index, long defaultValue) {
  557           try {
  558               return getLong(index);
  559           } catch (Exception e) {
  560               return defaultValue;
  561           }
  562       }
  563   
  564   
  565       /**
  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.
  569        *
  570        * @param index The index must be between 0 and length() - 1.
  571        * @return      A String value.
  572        */
  573       public String optString(int index) {
  574           return optString(index, "");
  575       }
  576   
  577   
  578       /**
  579        * Get the optional string associated with an index.
  580        * The defaultValue is returned if the key is not found.
  581        *
  582        * @param index The index must be between 0 and length() - 1.
  583        * @param defaultValue     The default value.
  584        * @return      A String value.
  585        */
  586       public String optString(int index, String defaultValue) {
  587           Object o = opt(index);
  588           return o != null ? o.toString() : defaultValue;
  589       }
  590   
  591   
  592       /**
  593        * Append a boolean value. This increases the array's length by one.
  594        *
  595        * @param value A boolean value.
  596        * @return this.
  597        */
  598       public JSONArray put(boolean value) {
  599           put(value ? Boolean.TRUE : Boolean.FALSE);
  600           return this;
  601       }
  602   
  603   
  604       /**
  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.
  608        * @return      this.
  609        */
  610       public JSONArray put(Collection value) {
  611           put(new JSONArray(value));
  612           return this;
  613       }
  614   
  615   
  616       /**
  617        * Append a double value. This increases the array's length by one.
  618        *
  619        * @param value A double value.
  620        * @throws JSONException if the value is not finite.
  621        * @return this.
  622        */
  623       public JSONArray put(double value) throws JSONException {
  624           Double d = new Double(value);
  625           JSONObject.testValidity(d);
  626           put(d);
  627           return this;
  628       }
  629   
  630   
  631       /**
  632        * Append an int value. This increases the array's length by one.
  633        *
  634        * @param value An int value.
  635        * @return this.
  636        */
  637       public JSONArray put(int value) {
  638           put(new Integer(value));
  639           return this;
  640       }
  641   
  642   
  643       /**
  644        * Append an long value. This increases the array's length by one.
  645        *
  646        * @param value A long value.
  647        * @return this.
  648        */
  649       public JSONArray put(long value) {
  650           put(new Long(value));
  651           return this;
  652       }
  653   
  654   
  655       /**
  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.
  659        * @return      this.
  660        */
  661       public JSONArray put(Map value) {
  662           put(new JSONObject(value));
  663           return this;
  664       }
  665   
  666   
  667       /**
  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.
  672        * @return this.
  673        */
  674       public JSONArray put(Object value) {
  675           this.myArrayList.add(value);
  676           return this;
  677       }
  678   
  679   
  680       /**
  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.
  686        * @return this.
  687        * @throws JSONException If the index is negative.
  688        */
  689       public JSONArray put(int index, boolean value) throws JSONException {
  690           put(index, value ? Boolean.TRUE : Boolean.FALSE);
  691           return this;
  692       }
  693   
  694   
  695       /**
  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.
  700        * @return      this.
  701        * @throws JSONException If the index is negative or if the value is
  702        * not finite.
  703        */
  704       public JSONArray put(int index, Collection value) throws JSONException {
  705           put(index, new JSONArray(value));
  706           return this;
  707       }
  708   
  709   
  710       /**
  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
  713        *  it out.
  714        * @param index The subscript.
  715        * @param value A double value.
  716        * @return this.
  717        * @throws JSONException If the index is negative or if the value is
  718        * not finite.
  719        */
  720       public JSONArray put(int index, double value) throws JSONException {
  721           put(index, new Double(value));
  722           return this;
  723       }
  724   
  725   
  726       /**
  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
  729        *  it out.
  730        * @param index The subscript.
  731        * @param value An int value.
  732        * @return this.
  733        * @throws JSONException If the index is negative.
  734        */
  735       public JSONArray put(int index, int value) throws JSONException {
  736           put(index, new Integer(value));
  737           return this;
  738       }
  739   
  740   
  741       /**
  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
  744        *  it out.
  745        * @param index The subscript.
  746        * @param value A long value.
  747        * @return this.
  748        * @throws JSONException If the index is negative.
  749        */
  750       public JSONArray put(int index, long value) throws JSONException {
  751           put(index, new Long(value));
  752           return this;
  753       }
  754   
  755   
  756       /**
  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.
  761        * @return      this.
  762        * @throws JSONException If the index is negative or if the the value is
  763        *  an invalid number.
  764        */
  765       public JSONArray put(int index, Map value) throws JSONException {
  766           put(index, new JSONObject(value));
  767           return this;
  768       }
  769   
  770   
  771       /**
  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.
  779        * @return this.
  780        * @throws JSONException If the index is negative or if the the value is
  781        *  an invalid number.
  782        */
  783       public JSONArray put(int index, Object value) throws JSONException {
  784           JSONObject.testValidity(value);
  785           if (index < 0) {
  786               throw new JSONException("JSONArray[" + index + "] not found.");
  787           }
  788           if (index < length()) {
  789               this.myArrayList.set(index, value);
  790           } else {
  791               while (index != length()) {
  792                   put(JSONObject.NULL);
  793               }
  794               put(value);
  795           }
  796           return this;
  797       }
  798   
  799   
  800       /**
  801        * Produce a JSONObject by combining a JSONArray of names with the values
  802        * of this JSONArray.
  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
  806        * has no values.
  807        * @throws JSONException If any of the names are null.
  808        */
  809       public JSONObject toJSONObject(JSONArray names) throws JSONException {
  810           if (names == null || names.length() == 0 || length() == 0) {
  811               return null;
  812           }
  813           JSONObject jo = new JSONObject();
  814           for (int i = 0; i < names.length(); i += 1) {
  815               jo.put(names.getString(i), this.opt(i));
  816           }
  817           return jo;
  818       }
  819   
  820   
  821       /**
  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.
  826        * <p>
  827        * Warning: This method assumes that the data structure is acyclical.
  828        *
  829        * @return a printable, displayable, transmittable
  830        *  representation of the array.
  831        */
  832       public String toString() {
  833           try {
  834               return '[' + join(",") + ']';
  835           } catch (Exception e) {
  836               return null;
  837           }
  838       }
  839   
  840   
  841       /**
  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
  845        *  indentation.
  846        * @return a printable, displayable, transmittable
  847        *  representation of the object, beginning
  848        *  with <code>[</code>&nbsp;<small>(left bracket)</small> and ending
  849        *  with <code>]</code>&nbsp;<small>(right bracket)</small>.
  850        * @throws JSONException
  851        */
  852       public String toString(int indentFactor) throws JSONException {
  853           return toString(indentFactor, 0);
  854       }
  855   
  856   
  857       /**
  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
  861        *  indentation.
  862        * @param indent The indention of the top level.
  863        * @return a printable, displayable, transmittable
  864        *  representation of the array.
  865        * @throws JSONException
  866        */
  867       String toString(int indentFactor, int indent) throws JSONException {
  868           int len = length();
  869           if (len == 0) {
  870               return "[]";
  871           }
  872           int i;
  873           StringBuffer sb = new StringBuffer("[");
  874           if (len == 1) {
  875               sb.append(JSONObject.valueToString(this.myArrayList.get(0),
  876                       indentFactor, indent));
  877           } else {
  878               int newindent = indent + indentFactor;
  879               sb.append('\n');
  880               for (i = 0; i < len; i += 1) {
  881                   if (i > 0) {
  882                       sb.append(",\n");
  883                   }
  884                   for (int j = 0; j < newindent; j += 1) {
  885                       sb.append(' ');
  886                   }
  887                   sb.append(JSONObject.valueToString(this.myArrayList.get(i),
  888                           indentFactor, newindent));
  889               }
  890               sb.append('\n');
  891               for (i = 0; i < indent; i += 1) {
  892                   sb.append(' ');
  893               }
  894           }
  895           sb.append(']');
  896           return sb.toString();
  897       }
  898   
  899   
  900       /**
  901        * Write the contents of the JSONArray as JSON text to a writer.
  902        * For compactness, no whitespace is added.
  903        * <p>
  904        * Warning: This method assumes that the data structure is acyclical.
  905        *
  906        * @return The writer.
  907        * @throws JSONException
  908        */
  909       public Writer write(Writer writer) throws JSONException {
  910           try {
  911               boolean b = false;
  912               int     len = length();
  913   
  914               writer.write('[');
  915   
  916               for (int i = 0; i < len; i += 1) {
  917                   if (b) {
  918                       writer.write(',');
  919                   }
  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);
  925                   } else {
  926                       writer.write(JSONObject.valueToString(v));
  927                   }
  928                   b = true;
  929               }
  930               writer.write(']');
  931               return writer;
  932           } catch (IOException e) {
  933              throw new JSONException(e);
  934           }
  935       }
  936   }

Home » apache-tomcat-6.0.26-src » org.apache » tomcat » util » json » [javadoc | source]