Guest User

Untitled

a guest
Jun 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 56.04 KB | None | 0 0
  1. package org.treckba;
  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.Field;
  30. import java.lang.reflect.Modifier;
  31. import java.lang.reflect.Method;
  32. import java.util.Collection;
  33. import java.util.Enumeration;
  34. import java.util.HashMap;
  35. import java.util.Iterator;
  36. import java.util.Locale;
  37. import java.util.Map;
  38. import java.util.ResourceBundle;
  39.  
  40. /**
  41.  * A JSONObject is an unordered collection of name/value pairs. Its
  42.  * external form is a string wrapped in curly braces with colons between the
  43.  * names and values, and commas between the values and names. The internal form
  44.  * is an object having <code>get</code> and <code>opt</code> methods for
  45.  * accessing the values by name, and <code>put</code> methods for adding or
  46.  * replacing values by name. The values can be any of these types:
  47.  * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
  48.  * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code>
  49.  * object. A JSONObject constructor can be used to convert an external form
  50.  * JSON text into an internal form whose values can be retrieved with the
  51.  * <code>get</code> and <code>opt</code> methods, or to convert values into a
  52.  * JSON text using the <code>put</code> and <code>toString</code> methods.
  53.  * A <code>get</code> method returns a value if one can be found, and throws an
  54.  * exception if one cannot be found. An <code>opt</code> method returns a
  55.  * default value instead of throwing an exception, and so is useful for
  56.  * obtaining optional values.
  57.  * <p>
  58.  * The generic <code>get()</code> and <code>opt()</code> methods return an
  59.  * object, which you can cast or query for type. There are also typed
  60.  * <code>get</code> and <code>opt</code> methods that do type checking and type
  61.  * coercion for you. The opt methods differ from the get methods in that they
  62.  * do not throw. Instead, they return a specified value, such as null.
  63.  * <p>
  64.  * The <code>put</code> methods add or replace values in an object. For example,
  65.  * <pre>myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre>
  66.  * produces the string <code>{"JSON": "Hello, World"}</code>.
  67.  * <p>
  68.  * The texts produced by the <code>toString</code> methods strictly conform to
  69.  * the JSON syntax rules.
  70.  * The constructors are more forgiving in the texts they will accept:
  71.  * <ul>
  72.  * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just
  73.  *     before the closing brace.</li>
  74.  * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
  75.  *     quote)</small>.</li>
  76.  * <li>Strings do not need to be quoted at all if they do not begin with a quote
  77.  *     or single quote, and if they do not contain leading or trailing spaces,
  78.  *     and if they do not contain any of these characters:
  79.  *     <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
  80.  *     and if they are not the reserved words <code>true</code>,
  81.  *     <code>false</code>, or <code>null</code>.</li>
  82.  * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as
  83.  *     by <code>:</code>.</li>
  84.  * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as
  85.  *     well as by <code>,</code> <small>(comma)</small>.</li>
  86.  * </ul>
  87.  * @author JSON.org
  88.  * @version 2011-11-24
  89.  */
  90. public class JSONObject {
  91.  
  92.     /**
  93.      * JSONObject.NULL is equivalent to the value that JavaScript calls null,
  94.      * whilst Java's null is equivalent to the value that JavaScript calls
  95.      * undefined.
  96.      */
  97.      private static final class Null {
  98.  
  99.         /**
  100.          * There is only intended to be a single instance of the NULL object,
  101.          * so the clone method returns itself.
  102.          * @return     NULL.
  103.          */
  104.         protected final Object clone() {
  105.             return this;
  106.         }
  107.  
  108.         /**
  109.          * A Null object is equal to the null value and to itself.
  110.          * @param object    An object to test for nullness.
  111.          * @return true if the object parameter is the JSONObject.NULL object
  112.          *  or null.
  113.          */
  114.         public boolean equals(Object object) {
  115.             return object == null || object == this;
  116.         }
  117.  
  118.         /**
  119.          * Get the "null" string value.
  120.          * @return The string "null".
  121.          */
  122.         public String toString() {
  123.             return "null";
  124.         }
  125.     }
  126.  
  127.  
  128.     /**
  129.      * The map where the JSONObject's properties are kept.
  130.      */
  131.     private final Map map;
  132.  
  133.  
  134.     /**
  135.      * It is sometimes more convenient and less ambiguous to have a
  136.      * <code>NULL</code> object than to use Java's <code>null</code> value.
  137.      * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
  138.      * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
  139.      */
  140.     public static final Object NULL = new Null();
  141.  
  142.  
  143.     /**
  144.      * Construct an empty JSONObject.
  145.      */
  146.     public JSONObject() {
  147.         this.map = new HashMap();
  148.     }
  149.  
  150.  
  151.     /**
  152.      * Construct a JSONObject from a subset of another JSONObject.
  153.      * An array of strings is used to identify the keys that should be copied.
  154.      * Missing keys are ignored.
  155.      * @param jo A JSONObject.
  156.      * @param names An array of strings.
  157.      * @throws JSONException
  158.      * @exception JSONException If a value is a non-finite number or if a name is duplicated.
  159.      */
  160.     public JSONObject(JSONObject jo, String[] names) {
  161.         this();
  162.         for (int i = 0; i < names.length; i += 1) {
  163.             try {
  164.                 this.putOnce(names[i], jo.opt(names[i]));
  165.             } catch (Exception ignore) {
  166.             }
  167.         }
  168.     }
  169.  
  170.  
  171.     /**
  172.      * Construct a JSONObject from a JSONTokener.
  173.      * @param x A JSONTokener object containing the source string.
  174.      * @throws JSONException If there is a syntax error in the source string
  175.      *  or a duplicated key.
  176.      */
  177.     public JSONObject(JSONTokener x) throws JSONException {
  178.         this();
  179.         char c;
  180.         String key;
  181.  
  182.         if (x.nextClean() != '{') {
  183.             throw x.syntaxError("A JSONObject text must begin with '{'");
  184.         }
  185.         for (;;) {
  186.             c = x.nextClean();
  187.             switch (c) {
  188.             case 0:
  189.                 throw x.syntaxError("A JSONObject text must end with '}'");
  190.             case '}':
  191.                 return;
  192.             default:
  193.                 x.back();
  194.                 key = x.nextValue().toString();
  195.             }
  196.  
  197. // The key is followed by ':'. We will also tolerate '=' or '=>'.
  198.  
  199.             c = x.nextClean();
  200.             if (c == '=') {
  201.                 if (x.next() != '>') {
  202.                     x.back();
  203.                 }
  204.             } else if (c != ':') {
  205.                 throw x.syntaxError("Expected a ':' after a key");
  206.             }
  207.             this.putOnce(key, x.nextValue());
  208.  
  209. // Pairs are separated by ','. We will also tolerate ';'.
  210.  
  211.             switch (x.nextClean()) {
  212.             case ';':
  213.             case ',':
  214.                 if (x.nextClean() == '}') {
  215.                     return;
  216.                 }
  217.                 x.back();
  218.                 break;
  219.             case '}':
  220.                 return;
  221.             default:
  222.                 throw x.syntaxError("Expected a ',' or '}'");
  223.             }
  224.         }
  225.     }
  226.  
  227.  
  228.     /**
  229.      * Construct a JSONObject from a Map.
  230.      *
  231.      * @param map A map object that can be used to initialize the contents of
  232.      *  the JSONObject.
  233.      * @throws JSONException
  234.      */
  235.     public JSONObject(Map map) {
  236.         this.map = new HashMap();
  237.         if (map != null) {
  238.             Iterator i = map.entrySet().iterator();
  239.             while (i.hasNext()) {
  240.                 Map.Entry e = (Map.Entry)i.next();
  241.                 Object value = e.getValue();
  242.                 if (value != null) {
  243.                     this.map.put(e.getKey(), wrap(value));
  244.                 }
  245.             }
  246.         }
  247.     }
  248.  
  249.  
  250.     /**
  251.      * Construct a JSONObject from an Object using bean getters.
  252.      * It reflects on all of the public methods of the object.
  253.      * For each of the methods with no parameters and a name starting
  254.      * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter,
  255.      * the method is invoked, and a key and the value returned from the getter method
  256.      * are put into the new JSONObject.
  257.      *
  258.      * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix.
  259.      * If the second remaining character is not upper case, then the first
  260.      * character is converted to lower case.
  261.      *
  262.      * For example, if an object has a method named <code>"getName"</code>, and
  263.      * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>,
  264.      * then the JSONObject will contain <code>"name": "Larry Fine"</code>.
  265.      *
  266.      * @param bean An object that has getter methods that should be used
  267.      * to make a JSONObject.
  268.      */
  269.     public JSONObject(Object bean) {
  270.         this();
  271.         this.populateMap(bean);
  272.     }
  273.  
  274.  
  275.     /**
  276.      * Construct a JSONObject from an Object, using reflection to find the
  277.      * public members. The resulting JSONObject's keys will be the strings
  278.      * from the names array, and the values will be the field values associated
  279.      * with those keys in the object. If a key is not found or not visible,
  280.      * then it will not be copied into the new JSONObject.
  281.      * @param object An object that has fields that should be used to make a
  282.      * JSONObject.
  283.      * @param names An array of strings, the names of the fields to be obtained
  284.      * from the object.
  285.      */
  286.     public JSONObject(Object object, String names[]) {
  287.         this();
  288.         Class c = object.getClass();
  289.         for (int i = 0; i < names.length; i += 1) {
  290.             String name = names[i];
  291.             try {
  292.                 this.putOpt(name, c.getField(name).get(object));
  293.             } catch (Exception ignore) {
  294.             }
  295.         }
  296.     }
  297.  
  298.  
  299.     /**
  300.      * Construct a JSONObject from a source JSON text string.
  301.      * This is the most commonly used JSONObject constructor.
  302.      * @param source    A string beginning
  303.      *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  304.      *  with <code>}</code>&nbsp;<small>(right brace)</small>.
  305.      * @exception JSONException If there is a syntax error in the source
  306.      *  string or a duplicated key.
  307.      */
  308.     public JSONObject(String source) throws JSONException {
  309.         this(new JSONTokener(source));
  310.     }
  311.  
  312.  
  313.     /**
  314.      * Construct a JSONObject from a ResourceBundle.
  315.      * @param baseName The ResourceBundle base name.
  316.      * @param locale The Locale to load the ResourceBundle for.
  317.      * @throws JSONException If any JSONExceptions are detected.
  318.      */
  319.     public JSONObject(String baseName, Locale locale) throws JSONException {
  320.         this();
  321.         ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
  322.                 Thread.currentThread().getContextClassLoader());
  323.  
  324. // Iterate through the keys in the bundle.
  325.  
  326.         Enumeration keys = bundle.getKeys();
  327.         while (keys.hasMoreElements()) {
  328.             Object key = keys.nextElement();
  329.             if (key instanceof String) {
  330.  
  331. // Go through the path, ensuring that there is a nested JSONObject for each
  332. // segment except the last. Add the value using the last segment's name into
  333. // the deepest nested JSONObject.
  334.  
  335.                 String[] path = ((String)key).split("\\.");
  336.                 int last = path.length - 1;
  337.                 JSONObject target = this;
  338.                 for (int i = 0; i < last; i += 1) {
  339.                     String segment = path[i];
  340.                     JSONObject nextTarget = target.optJSONObject(segment);
  341.                     if (nextTarget == null) {
  342.                         nextTarget = new JSONObject();
  343.                         target.put(segment, nextTarget);
  344.                     }
  345.                     target = nextTarget;
  346.                 }
  347.                 target.put(path[last], bundle.getString((String)key));
  348.             }
  349.         }
  350.     }
  351.  
  352.  
  353.     /**
  354.      * Accumulate values under a key. It is similar to the put method except
  355.      * that if there is already an object stored under the key then a
  356.      * JSONArray is stored under the key to hold all of the accumulated values.
  357.      * If there is already a JSONArray, then the new value is appended to it.
  358.      * In contrast, the put method replaces the previous value.
  359.      *
  360.      * If only one value is accumulated that is not a JSONArray, then the
  361.      * result will be the same as using put. But if multiple values are
  362.      * accumulated, then the result will be like append.
  363.      * @param key   A key string.
  364.      * @param value An object to be accumulated under the key.
  365.      * @return this.
  366.      * @throws JSONException If the value is an invalid number
  367.      *  or if the key is null.
  368.      */
  369.     public JSONObject accumulate(
  370.         String key,
  371.         Object value
  372.     ) throws JSONException {
  373.         testValidity(value);
  374.         Object object = this.opt(key);
  375.         if (object == null) {
  376.             this.put(key, value instanceof JSONArray
  377.                     ? new JSONArray().put(value)
  378.                     : value);
  379.         } else if (object instanceof JSONArray) {
  380.             ((JSONArray)object).put(value);
  381.         } else {
  382.             this.put(key, new JSONArray().put(object).put(value));
  383.         }
  384.         return this;
  385.     }
  386.  
  387.  
  388.     /**
  389.      * Append values to the array under a key. If the key does not exist in the
  390.      * JSONObject, then the key is put in the JSONObject with its value being a
  391.      * JSONArray containing the value parameter. If the key was already
  392.      * associated with a JSONArray, then the value parameter is appended to it.
  393.      * @param key   A key string.
  394.      * @param value An object to be accumulated under the key.
  395.      * @return this.
  396.      * @throws JSONException If the key is null or if the current value
  397.      *  associated with the key is not a JSONArray.
  398.      */
  399.     public JSONObject append(String key, Object value) throws JSONException {
  400.         testValidity(value);
  401.         Object object = this.opt(key);
  402.         if (object == null) {
  403.             this.put(key, new JSONArray().put(value));
  404.         } else if (object instanceof JSONArray) {
  405.             this.put(key, ((JSONArray)object).put(value));
  406.         } else {
  407.             throw new JSONException("JSONObject[" + key +
  408.                     "] is not a JSONArray.");
  409.         }
  410.         return this;
  411.     }
  412.  
  413.  
  414.     /**
  415.      * Produce a string from a double. The string "null" will be returned if
  416.      * the number is not finite.
  417.      * @param  d A double.
  418.      * @return A String.
  419.      */
  420.     public static String doubleToString(double d) {
  421.         if (Double.isInfinite(d) || Double.isNaN(d)) {
  422.             return "null";
  423.         }
  424.  
  425. // Shave off trailing zeros and decimal point, if possible.
  426.  
  427.         String string = Double.toString(d);
  428.         if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
  429.                 string.indexOf('E') < 0) {
  430.             while (string.endsWith("0")) {
  431.                 string = string.substring(0, string.length() - 1);
  432.             }
  433.             if (string.endsWith(".")) {
  434.                 string = string.substring(0, string.length() - 1);
  435.             }
  436.         }
  437.         return string;
  438.     }
  439.  
  440.  
  441.     /**
  442.      * Get the value object associated with a key.
  443.      *
  444.      * @param key   A key string.
  445.      * @return      The object associated with the key.
  446.      * @throws      JSONException if the key is not found.
  447.      */
  448.     public Object get(String key) throws JSONException {
  449.         if (key == null) {
  450.             throw new JSONException("Null key.");
  451.         }
  452.         Object object = this.opt(key);
  453.         if (object == null) {
  454.             throw new JSONException("JSONObject[" + quote(key) +
  455.                     "] not found.");
  456.         }
  457.         return object;
  458.     }
  459.  
  460.  
  461.     /**
  462.      * Get the boolean value associated with a key.
  463.      *
  464.      * @param key   A key string.
  465.      * @return      The truth.
  466.      * @throws      JSONException
  467.      *  if the value is not a Boolean or the String "true" or "false".
  468.      */
  469.     public boolean getBoolean(String key) throws JSONException {
  470.         Object object = this.get(key);
  471.         if (object.equals(Boolean.FALSE) ||
  472.                 (object instanceof String &&
  473.                 ((String)object).equalsIgnoreCase("false"))) {
  474.             return false;
  475.         } else if (object.equals(Boolean.TRUE) ||
  476.                 (object instanceof String &&
  477.                 ((String)object).equalsIgnoreCase("true"))) {
  478.             return true;
  479.         }
  480.         throw new JSONException("JSONObject[" + quote(key) +
  481.                 "] is not a Boolean.");
  482.     }
  483.  
  484.  
  485.     /**
  486.      * Get the double value associated with a key.
  487.      * @param key   A key string.
  488.      * @return      The numeric value.
  489.      * @throws JSONException if the key is not found or
  490.      *  if the value is not a Number object and cannot be converted to a number.
  491.      */
  492.     public double getDouble(String key) throws JSONException {
  493.         Object object = this.get(key);
  494.         try {
  495.             return object instanceof Number
  496.                 ? ((Number)object).doubleValue()
  497.                 : Double.parseDouble((String)object);
  498.         } catch (Exception e) {
  499.             throw new JSONException("JSONObject[" + quote(key) +
  500.                 "] is not a number.");
  501.         }
  502.     }
  503.  
  504.  
  505.     /**
  506.      * Get the int value associated with a key.
  507.      *
  508.      * @param key   A key string.
  509.      * @return      The integer value.
  510.      * @throws   JSONException if the key is not found or if the value cannot
  511.      *  be converted to an integer.
  512.      */
  513.     public int getInt(String key) throws JSONException {
  514.         Object object = this.get(key);
  515.         try {
  516.             return object instanceof Number
  517.                 ? ((Number)object).intValue()
  518.                 : Integer.parseInt((String)object);
  519.         } catch (Exception e) {
  520.             throw new JSONException("JSONObject[" + quote(key) +
  521.                 "] is not an int.");
  522.         }
  523.     }
  524.  
  525.  
  526.     /**
  527.      * Get the JSONArray value associated with a key.
  528.      *
  529.      * @param key   A key string.
  530.      * @return      A JSONArray which is the value.
  531.      * @throws      JSONException if the key is not found or
  532.      *  if the value is not a JSONArray.
  533.      */
  534.     public JSONArray getJSONArray(String key) throws JSONException {
  535.         Object object = this.get(key);
  536.         if (object instanceof JSONArray) {
  537.             return (JSONArray)object;
  538.         }
  539.         throw new JSONException("JSONObject[" + quote(key) +
  540.                 "] is not a JSONArray.");
  541.     }
  542.  
  543.  
  544.     /**
  545.      * Get the JSONObject value associated with a key.
  546.      *
  547.      * @param key   A key string.
  548.      * @return      A JSONObject which is the value.
  549.      * @throws      JSONException if the key is not found or
  550.      *  if the value is not a JSONObject.
  551.      */
  552.     public JSONObject getJSONObject(String key) throws JSONException {
  553.         Object object = this.get(key);
  554.         if (object instanceof JSONObject) {
  555.             return (JSONObject)object;
  556.         }
  557.         throw new JSONException("JSONObject[" + quote(key) +
  558.                 "] is not a JSONObject.");
  559.     }
  560.  
  561.  
  562.     /**
  563.      * Get the long value associated with a key.
  564.      *
  565.      * @param key   A key string.
  566.      * @return      The long value.
  567.      * @throws   JSONException if the key is not found or if the value cannot
  568.      *  be converted to a long.
  569.      */
  570.     public long getLong(String key) throws JSONException {
  571.         Object object = this.get(key);
  572.         try {
  573.             return object instanceof Number
  574.                 ? ((Number)object).longValue()
  575.                 : Long.parseLong((String)object);
  576.         } catch (Exception e) {
  577.             throw new JSONException("JSONObject[" + quote(key) +
  578.                 "] is not a long.");
  579.         }
  580.     }
  581.  
  582.  
  583.     /**
  584.      * Get an array of field names from a JSONObject.
  585.      *
  586.      * @return An array of field names, or null if there are no names.
  587.      */
  588.     public static String[] getNames(JSONObject jo) {
  589.         int length = jo.length();
  590.         if (length == 0) {
  591.             return null;
  592.         }
  593.         Iterator iterator = jo.keys();
  594.         String[] names = new String[length];
  595.         int i = 0;
  596.         while (iterator.hasNext()) {
  597.             names[i] = (String)iterator.next();
  598.             i += 1;
  599.         }
  600.         return names;
  601.     }
  602.  
  603.  
  604.     /**
  605.      * Get an array of field names from an Object.
  606.      *
  607.      * @return An array of field names, or null if there are no names.
  608.      */
  609.     public static String[] getNames(Object object) {
  610.         if (object == null) {
  611.             return null;
  612.         }
  613.         Class klass = object.getClass();
  614.         Field[] fields = klass.getFields();
  615.         int length = fields.length;
  616.         if (length == 0) {
  617.             return null;
  618.         }
  619.         String[] names = new String[length];
  620.         for (int i = 0; i < length; i += 1) {
  621.             names[i] = fields[i].getName();
  622.         }
  623.         return names;
  624.     }
  625.  
  626.  
  627.     /**
  628.      * Get the string associated with a key.
  629.      *
  630.      * @param key   A key string.
  631.      * @return      A string which is the value.
  632.      * @throws   JSONException if there is no string value for the key.
  633.      */
  634.     public String getString(String key) throws JSONException {
  635.         Object object = this.get(key);
  636.         if (object instanceof String) {
  637.             return (String)object;
  638.         }
  639.         throw new JSONException("JSONObject[" + quote(key) +
  640.             "] not a string.");
  641.     }
  642.  
  643.  
  644.     /**
  645.      * Determine if the JSONObject contains a specific key.
  646.      * @param key   A key string.
  647.      * @return      true if the key exists in the JSONObject.
  648.      */
  649.     public boolean has(String key) {
  650.         return this.map.containsKey(key);
  651.     }
  652.  
  653.  
  654.     /**
  655.      * Increment a property of a JSONObject. If there is no such property,
  656.      * create one with a value of 1. If there is such a property, and if
  657.      * it is an Integer, Long, Double, or Float, then add one to it.
  658.      * @param key  A key string.
  659.      * @return this.
  660.      * @throws JSONException If there is already a property with this name
  661.      * that is not an Integer, Long, Double, or Float.
  662.      */
  663.     public JSONObject increment(String key) throws JSONException {
  664.         Object value = this.opt(key);
  665.         if (value == null) {
  666.             this.put(key, 1);
  667.         } else if (value instanceof Integer) {
  668.             this.put(key, ((Integer)value).intValue() + 1);
  669.         } else if (value instanceof Long) {
  670.             this.put(key, ((Long)value).longValue() + 1);
  671.         } else if (value instanceof Double) {
  672.             this.put(key, ((Double)value).doubleValue() + 1);
  673.         } else if (value instanceof Float) {
  674.             this.put(key, ((Float)value).floatValue() + 1);
  675.         } else {
  676.             throw new JSONException("Unable to increment [" + quote(key) + "].");
  677.         }
  678.         return this;
  679.     }
  680.  
  681.  
  682.     /**
  683.      * Determine if the value associated with the key is null or if there is
  684.      *  no value.
  685.      * @param key   A key string.
  686.      * @return      true if there is no value associated with the key or if
  687.      *  the value is the JSONObject.NULL object.
  688.      */
  689.     public boolean isNull(String key) {
  690.         return JSONObject.NULL.equals(this.opt(key));
  691.     }
  692.  
  693.  
  694.     /**
  695.      * Get an enumeration of the keys of the JSONObject.
  696.      *
  697.      * @return An iterator of the keys.
  698.      */
  699.     public Iterator keys() {
  700.         return this.map.keySet().iterator();
  701.     }
  702.  
  703.  
  704.     /**
  705.      * Get the number of keys stored in the JSONObject.
  706.      *
  707.      * @return The number of keys in the JSONObject.
  708.      */
  709.     public int length() {
  710.         return this.map.size();
  711.     }
  712.  
  713.  
  714.     /**
  715.      * Produce a JSONArray containing the names of the elements of this
  716.      * JSONObject.
  717.      * @return A JSONArray containing the key strings, or null if the JSONObject
  718.      * is empty.
  719.      */
  720.     public JSONArray names() {
  721.         JSONArray ja = new JSONArray();
  722.         Iterator  keys = this.keys();
  723.         while (keys.hasNext()) {
  724.             ja.put(keys.next());
  725.         }
  726.         return ja.length() == 0 ? null : ja;
  727.     }
  728.  
  729.     /**
  730.      * Produce a string from a Number.
  731.      * @param  number A Number
  732.      * @return A String.
  733.      * @throws JSONException If n is a non-finite number.
  734.      */
  735.     public static String numberToString(Number number)
  736.             throws JSONException {
  737.         if (number == null) {
  738.             throw new JSONException("Null pointer");
  739.         }
  740.         testValidity(number);
  741.  
  742. // Shave off trailing zeros and decimal point, if possible.
  743.  
  744.         String string = number.toString();
  745.         if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
  746.                 string.indexOf('E') < 0) {
  747.             while (string.endsWith("0")) {
  748.                 string = string.substring(0, string.length() - 1);
  749.             }
  750.             if (string.endsWith(".")) {
  751.                 string = string.substring(0, string.length() - 1);
  752.             }
  753.         }
  754.         return string;
  755.     }
  756.  
  757.  
  758.     /**
  759.      * Get an optional value associated with a key.
  760.      * @param key   A key string.
  761.      * @return      An object which is the value, or null if there is no value.
  762.      */
  763.     public Object opt(String key) {
  764.         return key == null ? null : this.map.get(key);
  765.     }
  766.  
  767.  
  768.     /**
  769.      * Get an optional boolean associated with a key.
  770.      * It returns false if there is no such key, or if the value is not
  771.      * Boolean.TRUE or the String "true".
  772.      *
  773.      * @param key   A key string.
  774.      * @return      The truth.
  775.      */
  776.     public boolean optBoolean(String key) {
  777.         return this.optBoolean(key, false);
  778.     }
  779.  
  780.  
  781.     /**
  782.      * Get an optional boolean associated with a key.
  783.      * It returns the defaultValue if there is no such key, or if it is not
  784.      * a Boolean or the String "true" or "false" (case insensitive).
  785.      *
  786.      * @param key              A key string.
  787.      * @param defaultValue     The default.
  788.      * @return      The truth.
  789.      */
  790.     public boolean optBoolean(String key, boolean defaultValue) {
  791.         try {
  792.             return this.getBoolean(key);
  793.         } catch (Exception e) {
  794.             return defaultValue;
  795.         }
  796.     }
  797.  
  798.  
  799.     /**
  800.      * Get an optional double associated with a key,
  801.      * or NaN if there is no such key or if its value is not a number.
  802.      * If the value is a string, an attempt will be made to evaluate it as
  803.      * a number.
  804.      *
  805.      * @param key   A string which is the key.
  806.      * @return      An object which is the value.
  807.      */
  808.     public double optDouble(String key) {
  809.         return this.optDouble(key, Double.NaN);
  810.     }
  811.  
  812.  
  813.     /**
  814.      * Get an optional double associated with a key, or the
  815.      * defaultValue if there is no such key or if its value is not a number.
  816.      * If the value is a string, an attempt will be made to evaluate it as
  817.      * a number.
  818.      *
  819.      * @param key   A key string.
  820.      * @param defaultValue     The default.
  821.      * @return      An object which is the value.
  822.      */
  823.     public double optDouble(String key, double defaultValue) {
  824.         try {
  825.             return this.getDouble(key);
  826.         } catch (Exception e) {
  827.             return defaultValue;
  828.         }
  829.     }
  830.  
  831.  
  832.     /**
  833.      * Get an optional int value associated with a key,
  834.      * or zero if there is no such key or if the value is not a number.
  835.      * If the value is a string, an attempt will be made to evaluate it as
  836.      * a number.
  837.      *
  838.      * @param key   A key string.
  839.      * @return      An object which is the value.
  840.      */
  841.     public int optInt(String key) {
  842.         return this.optInt(key, 0);
  843.     }
  844.  
  845.  
  846.     /**
  847.      * Get an optional int value associated with a key,
  848.      * or the default if there is no such key or if the value is not a number.
  849.      * If the value is a string, an attempt will be made to evaluate it as
  850.      * a number.
  851.      *
  852.      * @param key   A key string.
  853.      * @param defaultValue     The default.
  854.      * @return      An object which is the value.
  855.      */
  856.     public int optInt(String key, int defaultValue) {
  857.         try {
  858.             return this.getInt(key);
  859.         } catch (Exception e) {
  860.             return defaultValue;
  861.         }
  862.     }
  863.  
  864.  
  865.     /**
  866.      * Get an optional JSONArray associated with a key.
  867.      * It returns null if there is no such key, or if its value is not a
  868.      * JSONArray.
  869.      *
  870.      * @param key   A key string.
  871.      * @return      A JSONArray which is the value.
  872.      */
  873.     public JSONArray optJSONArray(String key) {
  874.         Object o = this.opt(key);
  875.         return o instanceof JSONArray ? (JSONArray)o : null;
  876.     }
  877.  
  878.  
  879.     /**
  880.      * Get an optional JSONObject associated with a key.
  881.      * It returns null if there is no such key, or if its value is not a
  882.      * JSONObject.
  883.      *
  884.      * @param key   A key string.
  885.      * @return      A JSONObject which is the value.
  886.      */
  887.     public JSONObject optJSONObject(String key) {
  888.         Object object = this.opt(key);
  889.         return object instanceof JSONObject ? (JSONObject)object : null;
  890.     }
  891.  
  892.  
  893.     /**
  894.      * Get an optional long value associated with a key,
  895.      * or zero if there is no such key or if the value is not a number.
  896.      * If the value is a string, an attempt will be made to evaluate it as
  897.      * a number.
  898.      *
  899.      * @param key   A key string.
  900.      * @return      An object which is the value.
  901.      */
  902.     public long optLong(String key) {
  903.         return this.optLong(key, 0);
  904.     }
  905.  
  906.  
  907.     /**
  908.      * Get an optional long value associated with a key,
  909.      * or the default if there is no such key or if the value is not a number.
  910.      * If the value is a string, an attempt will be made to evaluate it as
  911.      * a number.
  912.      *
  913.      * @param key          A key string.
  914.      * @param defaultValue The default.
  915.      * @return             An object which is the value.
  916.      */
  917.     public long optLong(String key, long defaultValue) {
  918.         try {
  919.             return this.getLong(key);
  920.         } catch (Exception e) {
  921.             return defaultValue;
  922.         }
  923.     }
  924.  
  925.  
  926.     /**
  927.      * Get an optional string associated with a key.
  928.      * It returns an empty string if there is no such key. If the value is not
  929.      * a string and is not null, then it is converted to a string.
  930.      *
  931.      * @param key   A key string.
  932.      * @return      A string which is the value.
  933.      */
  934.     public String optString(String key) {
  935.         return this.optString(key, "");
  936.     }
  937.  
  938.  
  939.     /**
  940.      * Get an optional string associated with a key.
  941.      * It returns the defaultValue if there is no such key.
  942.      *
  943.      * @param key   A key string.
  944.      * @param defaultValue     The default.
  945.      * @return      A string which is the value.
  946.      */
  947.     public String optString(String key, String defaultValue) {
  948.         Object object = this.opt(key);
  949.         return NULL.equals(object) ? defaultValue : object.toString();
  950.     }
  951.  
  952.  
  953.     private void populateMap(Object bean) {
  954.         Class klass = bean.getClass();
  955.  
  956. // If klass is a System class then set includeSuperClass to false.
  957.  
  958.         boolean includeSuperClass = klass.getClassLoader() != null;
  959.  
  960.         Method[] methods = includeSuperClass
  961.                 ? klass.getMethods()
  962.                 : klass.getDeclaredMethods();
  963.         for (int i = 0; i < methods.length; i += 1) {
  964.             try {
  965.                 Method method = methods[i];
  966.                 if (Modifier.isPublic(method.getModifiers())) {
  967.                     String name = method.getName();
  968.                     String key = "";
  969.                     if (name.startsWith("get")) {
  970.                         if ("getClass".equals(name) ||
  971.                                 "getDeclaringClass".equals(name)) {
  972.                             key = "";
  973.                         } else {
  974.                             key = name.substring(3);
  975.                         }
  976.                     } else if (name.startsWith("is")) {
  977.                         key = name.substring(2);
  978.                     }
  979.                     if (key.length() > 0 &&
  980.                             Character.isUpperCase(key.charAt(0)) &&
  981.                             method.getParameterTypes().length == 0) {
  982.                         if (key.length() == 1) {
  983.                             key = key.toLowerCase();
  984.                         } else if (!Character.isUpperCase(key.charAt(1))) {
  985.                             key = key.substring(0, 1).toLowerCase() +
  986.                                 key.substring(1);
  987.                         }
  988.  
  989.                         Object result = method.invoke(bean, (Object[])null);
  990.                         if (result != null) {
  991.                             this.map.put(key, wrap(result));
  992.                         }
  993.                     }
  994.                 }
  995.             } catch (Exception ignore) {
  996.             }
  997.         }
  998.     }
  999.  
  1000.  
  1001.     /**
  1002.      * Put a key/boolean pair in the JSONObject.
  1003.      *
  1004.      * @param key   A key string.
  1005.      * @param value A boolean which is the value.
  1006.      * @return this.
  1007.      * @throws JSONException If the key is null.
  1008.      */
  1009.     public JSONObject put(String key, boolean value) throws JSONException {
  1010.         this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
  1011.         return this;
  1012.     }
  1013.  
  1014.  
  1015.     /**
  1016.      * Put a key/value pair in the JSONObject, where the value will be a
  1017.      * JSONArray which is produced from a Collection.
  1018.      * @param key   A key string.
  1019.      * @param value A Collection value.
  1020.      * @return      this.
  1021.      * @throws JSONException
  1022.      */
  1023.     public JSONObject put(String key, Collection value) throws JSONException {
  1024.         this.put(key, new JSONArray(value));
  1025.         return this;
  1026.     }
  1027.  
  1028.  
  1029.     /**
  1030.      * Put a key/double pair in the JSONObject.
  1031.      *
  1032.      * @param key   A key string.
  1033.      * @param value A double which is the value.
  1034.      * @return this.
  1035.      * @throws JSONException If the key is null or if the number is invalid.
  1036.      */
  1037.     public JSONObject put(String key, double value) throws JSONException {
  1038.         this.put(key, new Double(value));
  1039.         return this;
  1040.     }
  1041.  
  1042.  
  1043.     /**
  1044.      * Put a key/int pair in the JSONObject.
  1045.      *
  1046.      * @param key   A key string.
  1047.      * @param value An int which is the value.
  1048.      * @return this.
  1049.      * @throws JSONException If the key is null.
  1050.      */
  1051.     public JSONObject put(String key, int value) throws JSONException {
  1052.         this.put(key, new Integer(value));
  1053.         return this;
  1054.     }
  1055.  
  1056.  
  1057.     /**
  1058.      * Put a key/long pair in the JSONObject.
  1059.      *
  1060.      * @param key   A key string.
  1061.      * @param value A long which is the value.
  1062.      * @return this.
  1063.      * @throws JSONException If the key is null.
  1064.      */
  1065.     public JSONObject put(String key, long value) throws JSONException {
  1066.         this.put(key, new Long(value));
  1067.         return this;
  1068.     }
  1069.  
  1070.  
  1071.     /**
  1072.      * Put a key/value pair in the JSONObject, where the value will be a
  1073.      * JSONObject which is produced from a Map.
  1074.      * @param key   A key string.
  1075.      * @param value A Map value.
  1076.      * @return      this.
  1077.      * @throws JSONException
  1078.      */
  1079.     public JSONObject put(String key, Map value) throws JSONException {
  1080.         this.put(key, new JSONObject(value));
  1081.         return this;
  1082.     }
  1083.  
  1084.  
  1085.     /**
  1086.      * Put a key/value pair in the JSONObject. If the value is null,
  1087.      * then the key will be removed from the JSONObject if it is present.
  1088.      * @param key   A key string.
  1089.      * @param value An object which is the value. It should be of one of these
  1090.      *  types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
  1091.      *  or the JSONObject.NULL object.
  1092.      * @return this.
  1093.      * @throws JSONException If the value is non-finite number
  1094.      *  or if the key is null.
  1095.      */
  1096.     public JSONObject put(String key, Object value) throws JSONException {
  1097.         if (key == null) {
  1098.             throw new JSONException("Null key.");
  1099.         }
  1100.         if (value != null) {
  1101.             testValidity(value);
  1102.             this.map.put(key, value);
  1103.         } else {
  1104.             this.remove(key);
  1105.         }
  1106.         return this;
  1107.     }
  1108.  
  1109.  
  1110.     /**
  1111.      * Put a key/value pair in the JSONObject, but only if the key and the
  1112.      * value are both non-null, and only if there is not already a member
  1113.      * with that name.
  1114.      * @param key
  1115.      * @param value
  1116.      * @return his.
  1117.      * @throws JSONException if the key is a duplicate
  1118.      */
  1119.     public JSONObject putOnce(String key, Object value) throws JSONException {
  1120.         if (key != null && value != null) {
  1121.             if (this.opt(key) != null) {
  1122.                 throw new JSONException("Duplicate key \"" + key + "\"");
  1123.             }
  1124.             this.put(key, value);
  1125.         }
  1126.         return this;
  1127.     }
  1128.  
  1129.  
  1130.     /**
  1131.      * Put a key/value pair in the JSONObject, but only if the
  1132.      * key and the value are both non-null.
  1133.      * @param key   A key string.
  1134.      * @param value An object which is the value. It should be of one of these
  1135.      *  types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
  1136.      *  or the JSONObject.NULL object.
  1137.      * @return this.
  1138.      * @throws JSONException If the value is a non-finite number.
  1139.      */
  1140.     public JSONObject putOpt(String key, Object value) throws JSONException {
  1141.         if (key != null && value != null) {
  1142.             this.put(key, value);
  1143.         }
  1144.         return this;
  1145.     }
  1146.  
  1147.  
  1148.     /**
  1149.      * Produce a string in double quotes with backslash sequences in all the
  1150.      * right places. A backslash will be inserted within </, producing <\/,
  1151.      * allowing JSON text to be delivered in HTML. In JSON text, a string
  1152.      * cannot contain a control character or an unescaped quote or backslash.
  1153.      * @param string A String
  1154.      * @return  A String correctly formatted for insertion in a JSON text.
  1155.      */
  1156.     public static String quote(String string) {
  1157.         if (string == null || string.length() == 0) {
  1158.             return "\"\"";
  1159.         }
  1160.  
  1161.         char         b;
  1162.         char         c = 0;
  1163.         String       hhhh;
  1164.         int          i;
  1165.         int          len = string.length();
  1166.         StringBuffer sb = new StringBuffer(len + 4);
  1167.  
  1168.         sb.append('"');
  1169.         for (i = 0; i < len; i += 1) {
  1170.             b = c;
  1171.             c = string.charAt(i);
  1172.             switch (c) {
  1173.             case '\\':
  1174.             case '"':
  1175.                 sb.append('\\');
  1176.                 sb.append(c);
  1177.                 break;
  1178.             case '/':
  1179.                 if (b == '<') {
  1180.                     sb.append('\\');
  1181.                 }
  1182.                 sb.append(c);
  1183.                 break;
  1184.             case '\b':
  1185.                 sb.append("\\b");
  1186.                 break;
  1187.             case '\t':
  1188.                 sb.append("\\t");
  1189.                 break;
  1190.             case '\n':
  1191.                 sb.append("\\n");
  1192.                 break;
  1193.             case '\f':
  1194.                 sb.append("\\f");
  1195.                 break;
  1196.             case '\r':
  1197.                 sb.append("\\r");
  1198.                 break;
  1199.             default:
  1200.                 if (c < ' ' || (c >= '\u0080' && c < '\u00a0') ||
  1201.                                (c >= '\u2000' && c < '\u2100')) {
  1202.                     hhhh = "000" + Integer.toHexString(c);
  1203.                     sb.append("\\u" + hhhh.substring(hhhh.length() - 4));
  1204.                 } else {
  1205.                     sb.append(c);
  1206.                 }
  1207.             }
  1208.         }
  1209.         sb.append('"');
  1210.         return sb.toString();
  1211.     }
  1212.  
  1213.     /**
  1214.      * Remove a name and its value, if present.
  1215.      * @param key The name to be removed.
  1216.      * @return The value that was associated with the name,
  1217.      * or null if there was no value.
  1218.      */
  1219.     public Object remove(String key) {
  1220.         return this.map.remove(key);
  1221.     }
  1222.  
  1223.     /**
  1224.      * Try to convert a string into a number, boolean, or null. If the string
  1225.      * can't be converted, return the string.
  1226.      * @param string A String.
  1227.      * @return A simple JSON value.
  1228.      */
  1229.     public static Object stringToValue(String string) {
  1230.         Double d;
  1231.         if (string.equals("")) {
  1232.             return string;
  1233.         }
  1234.         if (string.equalsIgnoreCase("true")) {
  1235.             return Boolean.TRUE;
  1236.         }
  1237.         if (string.equalsIgnoreCase("false")) {
  1238.             return Boolean.FALSE;
  1239.         }
  1240.         if (string.equalsIgnoreCase("null")) {
  1241.             return JSONObject.NULL;
  1242.         }
  1243.  
  1244.         /*
  1245.          * If it might be a number, try converting it.
  1246.          * If a number cannot be produced, then the value will just
  1247.          * be a string. Note that the plus and implied string
  1248.          * conventions are non-standard. A JSON parser may accept
  1249.          * non-JSON forms as long as it accepts all correct JSON forms.
  1250.          */
  1251.  
  1252.         char b = string.charAt(0);
  1253.         if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
  1254.             try {
  1255.                 if (string.indexOf('.') > -1 ||
  1256.                         string.indexOf('e') > -1 || string.indexOf('E') > -1) {
  1257.                     d = Double.valueOf(string);
  1258.                     if (!d.isInfinite() && !d.isNaN()) {
  1259.                         return d;
  1260.                     }
  1261.                 } else {
  1262.                     Long myLong = new Long(string);
  1263.                     if (myLong.longValue() == myLong.intValue()) {
  1264.                         return new Integer(myLong.intValue());
  1265.                     } else {
  1266.                         return myLong;
  1267.                     }
  1268.                 }
  1269.             }  catch (Exception ignore) {
  1270.             }
  1271.         }
  1272.         return string;
  1273.     }
  1274.  
  1275.  
  1276.     /**
  1277.      * Throw an exception if the object is a NaN or infinite number.
  1278.      * @param o The object to test.
  1279.      * @throws JSONException If o is a non-finite number.
  1280.      */
  1281.     public static void testValidity(Object o) throws JSONException {
  1282.         if (o != null) {
  1283.             if (o instanceof Double) {
  1284.                 if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
  1285.                     throw new JSONException(
  1286.                         "JSON does not allow non-finite numbers.");
  1287.                 }
  1288.             } else if (o instanceof Float) {
  1289.                 if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
  1290.                     throw new JSONException(
  1291.                         "JSON does not allow non-finite numbers.");
  1292.                 }
  1293.             }
  1294.         }
  1295.     }
  1296.  
  1297.  
  1298.     /**
  1299.      * Produce a JSONArray containing the values of the members of this
  1300.      * JSONObject.
  1301.      * @param names A JSONArray containing a list of key strings. This
  1302.      * determines the sequence of the values in the result.
  1303.      * @return A JSONArray of values.
  1304.      * @throws JSONException If any of the values are non-finite numbers.
  1305.      */
  1306.     public JSONArray toJSONArray(JSONArray names) throws JSONException {
  1307.         if (names == null || names.length() == 0) {
  1308.             return null;
  1309.         }
  1310.         JSONArray ja = new JSONArray();
  1311.         for (int i = 0; i < names.length(); i += 1) {
  1312.             ja.put(this.opt(names.getString(i)));
  1313.         }
  1314.         return ja;
  1315.     }
  1316.  
  1317.     /**
  1318.      * Make a JSON text of this JSONObject. For compactness, no whitespace
  1319.      * is added. If this would not result in a syntactically correct JSON text,
  1320.      * then null will be returned instead.
  1321.      * <p>
  1322.      * Warning: This method assumes that the data structure is acyclical.
  1323.      *
  1324.      * @return a printable, displayable, portable, transmittable
  1325.      *  representation of the object, beginning
  1326.      *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1327.      *  with <code>}</code>&nbsp;<small>(right brace)</small>.
  1328.      */
  1329.     public String toString() {
  1330.         try {
  1331.             Iterator     keys = this.keys();
  1332.             StringBuffer sb = new StringBuffer("{");
  1333.  
  1334.             while (keys.hasNext()) {
  1335.                 if (sb.length() > 1) {
  1336.                     sb.append(',');
  1337.                 }
  1338.                 Object o = keys.next();
  1339.                 sb.append(quote(o.toString()));
  1340.                 sb.append(':');
  1341.                 sb.append(valueToString(this.map.get(o)));
  1342.             }
  1343.             sb.append('}');
  1344.             return sb.toString();
  1345.         } catch (Exception e) {
  1346.             return null;
  1347.         }
  1348.     }
  1349.  
  1350.  
  1351.     /**
  1352.      * Make a prettyprinted JSON text of this JSONObject.
  1353.      * <p>
  1354.      * Warning: This method assumes that the data structure is acyclical.
  1355.      * @param indentFactor The number of spaces to add to each level of
  1356.      *  indentation.
  1357.      * @return a printable, displayable, portable, transmittable
  1358.      *  representation of the object, beginning
  1359.      *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1360.      *  with <code>}</code>&nbsp;<small>(right brace)</small>.
  1361.      * @throws JSONException If the object contains an invalid number.
  1362.      */
  1363.     public String toString(int indentFactor) throws JSONException {
  1364.         return this.toString(indentFactor, 0);
  1365.     }
  1366.  
  1367.  
  1368.     /**
  1369.      * Make a prettyprinted JSON text of this JSONObject.
  1370.      * <p>
  1371.      * Warning: This method assumes that the data structure is acyclical.
  1372.      * @param indentFactor The number of spaces to add to each level of
  1373.      *  indentation.
  1374.      * @param indent The indentation of the top level.
  1375.      * @return a printable, displayable, transmittable
  1376.      *  representation of the object, beginning
  1377.      *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1378.      *  with <code>}</code>&nbsp;<small>(right brace)</small>.
  1379.      * @throws JSONException If the object contains an invalid number.
  1380.      */
  1381.     String toString(int indentFactor, int indent) throws JSONException {
  1382.         int i;
  1383.         int length = this.length();
  1384.         if (length == 0) {
  1385.             return "{}";
  1386.         }
  1387.         Iterator     keys = this.keys();
  1388.         int          newindent = indent + indentFactor;
  1389.         Object       object;
  1390.         StringBuffer sb = new StringBuffer("{");
  1391.         if (length == 1) {
  1392.             object = keys.next();
  1393.             sb.append(quote(object.toString()));
  1394.             sb.append(": ");
  1395.             sb.append(valueToString(this.map.get(object), indentFactor,
  1396.                     indent));
  1397.         } else {
  1398.             while (keys.hasNext()) {
  1399.                 object = keys.next();
  1400.                 if (sb.length() > 1) {
  1401.                     sb.append(",\n");
  1402.                 } else {
  1403.                     sb.append('\n');
  1404.                 }
  1405.                 for (i = 0; i < newindent; i += 1) {
  1406.                     sb.append(' ');
  1407.                 }
  1408.                 sb.append(quote(object.toString()));
  1409.                 sb.append(": ");
  1410.                 sb.append(valueToString(this.map.get(object), indentFactor,
  1411.                         newindent));
  1412.             }
  1413.             if (sb.length() > 1) {
  1414.                 sb.append('\n');
  1415.                 for (i = 0; i < indent; i += 1) {
  1416.                     sb.append(' ');
  1417.                 }
  1418.             }
  1419.         }
  1420.         sb.append('}');
  1421.         return sb.toString();
  1422.     }
  1423.  
  1424.  
  1425.     /**
  1426.      * Make a JSON text of an Object value. If the object has an
  1427.      * value.toJSONString() method, then that method will be used to produce
  1428.      * the JSON text. The method is required to produce a strictly
  1429.      * conforming text. If the object does not contain a toJSONString
  1430.      * method (which is the most common case), then a text will be
  1431.      * produced by other means. If the value is an array or Collection,
  1432.      * then a JSONArray will be made from it and its toJSONString method
  1433.      * will be called. If the value is a MAP, then a JSONObject will be made
  1434.      * from it and its toJSONString method will be called. Otherwise, the
  1435.      * value's toString method will be called, and the result will be quoted.
  1436.      *
  1437.      * <p>
  1438.      * Warning: This method assumes that the data structure is acyclical.
  1439.      * @param value The value to be serialized.
  1440.      * @return a printable, displayable, transmittable
  1441.      *  representation of the object, beginning
  1442.      *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1443.      *  with <code>}</code>&nbsp;<small>(right brace)</small>.
  1444.      * @throws JSONException If the value is or contains an invalid number.
  1445.      */
  1446.     public static String valueToString(Object value) throws JSONException {
  1447.         if (value == null || value.equals(null)) {
  1448.             return "null";
  1449.         }
  1450.         if (value instanceof JSONString) {
  1451.             Object object;
  1452.             try {
  1453.                 object = ((JSONString)value).toJSONString();
  1454.             } catch (Exception e) {
  1455.                 throw new JSONException(e);
  1456.             }
  1457.             if (object instanceof String) {
  1458.                 return (String)object;
  1459.             }
  1460.             throw new JSONException("Bad value from toJSONString: " + object);
  1461.         }
  1462.         if (value instanceof Number) {
  1463.             return numberToString((Number) value);
  1464.         }
  1465.         if (value instanceof Boolean || value instanceof JSONObject ||
  1466.                 value instanceof JSONArray) {
  1467.             return value.toString();
  1468.         }
  1469.         if (value instanceof Map) {
  1470.             return new JSONObject((Map)value).toString();
  1471.         }
  1472.         if (value instanceof Collection) {
  1473.             return new JSONArray((Collection)value).toString();
  1474.         }
  1475.         if (value.getClass().isArray()) {
  1476.             return new JSONArray(value).toString();
  1477.         }
  1478.         return quote(value.toString());
  1479.     }
  1480.  
  1481.  
  1482.     /**
  1483.      * Make a prettyprinted JSON text of an object value.
  1484.      * <p>
  1485.      * Warning: This method assumes that the data structure is acyclical.
  1486.      * @param value The value to be serialized.
  1487.      * @param indentFactor The number of spaces to add to each level of
  1488.      *  indentation.
  1489.      * @param indent The indentation of the top level.
  1490.      * @return a printable, displayable, transmittable
  1491.      *  representation of the object, beginning
  1492.      *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1493.      *  with <code>}</code>&nbsp;<small>(right brace)</small>.
  1494.      * @throws JSONException If the object contains an invalid number.
  1495.      */
  1496.      static String valueToString(
  1497.          Object value,
  1498.          int    indentFactor,
  1499.          int    indent
  1500.      ) throws JSONException {
  1501.         if (value == null || value.equals(null)) {
  1502.             return "null";
  1503.         }
  1504.         try {
  1505.             if (value instanceof JSONString) {
  1506.                 Object o = ((JSONString)value).toJSONString();
  1507.                 if (o instanceof String) {
  1508.                     return (String)o;
  1509.                 }
  1510.             }
  1511.         } catch (Exception ignore) {
  1512.         }
  1513.         if (value instanceof Number) {
  1514.             return numberToString((Number) value);
  1515.         }
  1516.         if (value instanceof Boolean) {
  1517.             return value.toString();
  1518.         }
  1519.         if (value instanceof JSONObject) {
  1520.             return ((JSONObject)value).toString(indentFactor, indent);
  1521.         }
  1522.         if (value instanceof JSONArray) {
  1523.             return ((JSONArray)value).toString(indentFactor, indent);
  1524.         }
  1525.         if (value instanceof Map) {
  1526.             return new JSONObject((Map)value).toString(indentFactor, indent);
  1527.         }
  1528.         if (value instanceof Collection) {
  1529.             return new JSONArray((Collection)value).toString(indentFactor, indent);
  1530.         }
  1531.         if (value.getClass().isArray()) {
  1532.             return new JSONArray(value).toString(indentFactor, indent);
  1533.         }
  1534.         return quote(value.toString());
  1535.     }
  1536.  
  1537.  
  1538.      /**
  1539.       * Wrap an object, if necessary. If the object is null, return the NULL
  1540.       * object. If it is an array or collection, wrap it in a JSONArray. If
  1541.       * it is a map, wrap it in a JSONObject. If it is a standard property
  1542.       * (Double, String, et al) then it is already wrapped. Otherwise, if it
  1543.       * comes from one of the java packages, turn it into a string. And if
  1544.       * it doesn't, try to wrap it in a JSONObject. If the wrapping fails,
  1545.       * then null is returned.
  1546.       *
  1547.       * @param object The object to wrap
  1548.       * @return The wrapped value
  1549.       */
  1550.      public static Object wrap(Object object) {
  1551.          try {
  1552.              if (object == null) {
  1553.                  return NULL;
  1554.              }
  1555.              if (object instanceof JSONObject || object instanceof JSONArray  ||
  1556.                      NULL.equals(object)      || object instanceof JSONString ||
  1557.                      object instanceof Byte   || object instanceof Character  ||
  1558.                      object instanceof Short  || object instanceof Integer    ||
  1559.                      object instanceof Long   || object instanceof Boolean    ||
  1560.                      object instanceof Float  || object instanceof Double     ||
  1561.                      object instanceof String) {
  1562.                  return object;
  1563.              }
  1564.  
  1565.              if (object instanceof Collection) {
  1566.                  return new JSONArray((Collection)object);
  1567.              }
  1568.              if (object.getClass().isArray()) {
  1569.                  return new JSONArray(object);
  1570.              }
  1571.              if (object instanceof Map) {
  1572.                  return new JSONObject((Map)object);
  1573.              }
  1574.              Package objectPackage = object.getClass().getPackage();
  1575.              String objectPackageName = objectPackage != null
  1576.                  ? objectPackage.getName()
  1577.                  : "";
  1578.              if (
  1579.                  objectPackageName.startsWith("java.") ||
  1580.                  objectPackageName.startsWith("javax.") ||
  1581.                  object.getClass().getClassLoader() == null
  1582.              ) {
  1583.                  return object.toString();
  1584.              }
  1585.              return new JSONObject(object);
  1586.          } catch(Exception exception) {
  1587.              return null;
  1588.          }
  1589.      }
  1590.  
  1591.  
  1592.      /**
  1593.       * Write the contents of the JSONObject as JSON text to a writer.
  1594.       * For compactness, no whitespace is added.
  1595.       * <p>
  1596.       * Warning: This method assumes that the data structure is acyclical.
  1597.       *
  1598.       * @return The writer.
  1599.       * @throws JSONException
  1600.       */
  1601.      public Writer write(Writer writer) throws JSONException {
  1602.         try {
  1603.             boolean  commanate = false;
  1604.             Iterator keys = this.keys();
  1605.             writer.write('{');
  1606.  
  1607.             while (keys.hasNext()) {
  1608.                 if (commanate) {
  1609.                     writer.write(',');
  1610.                 }
  1611.                 Object key = keys.next();
  1612.                 writer.write(quote(key.toString()));
  1613.                 writer.write(':');
  1614.                 Object value = this.map.get(key);
  1615.                 if (value instanceof JSONObject) {
  1616.                     ((JSONObject)value).write(writer);
  1617.                 } else if (value instanceof JSONArray) {
  1618.                     ((JSONArray)value).write(writer);
  1619.                 } else {
  1620.                     writer.write(valueToString(value));
  1621.                 }
  1622.                 commanate = true;
  1623.             }
  1624.             writer.write('}');
  1625.             return writer;
  1626.         } catch (IOException exception) {
  1627.             throw new JSONException(exception);
  1628.         }
  1629.      }
  1630. }
Add Comment
Please, Sign In to add comment