[
  {
    "path": ".gitignore",
    "content": "/target\n*.class\n*.jar\n.classpath\n.project\nin.json\n/.settings\n"
  },
  {
    "path": "README.md",
    "content": "# Overview\n\nThe best tool for using JSON docs with Hive is [rcongui's openx Hive-JSON-Serde](https://github.com/rcongiu/Hive-JSON-Serde).  When using that JSON Serde, you define your Hive schema based on the contents of the JSON.\n\nHive schemas understand arrays, maps and structs.  You can map a JSON array to a Hive array and a JSON \"object\" to either a Hive map or struct.  I prefer to map JSON objects to structs.\n\nThis tool will take a curated JSON document and generate the Hive schema (CREATE TABLE statement) for use with the openx Hive-JSON-Serde.  I say \"curated\" because you should ensure that every possible key is present (with some arbitrary value of the right data type) and that all arrays have at least one entry.\n\nIf the curated JSON example you provide has more than one entry in an array, *only the first one will be examined*, so you should ensure that it has all the fields.\n\nFor more information on using the openx Hive-JSON-SerDe, see my [blog post entry](http://thornydev.blogspot.com/2013/07/querying-json-records-via-hive.html).\n\n\n# Build\n\n    mvn package\n\nCreates `json-hive-schema-1.0.jar` and `json-hive-schema-1.0-jar-with-dependencies.jar` in the `target` directory.\n\n\n\n# Usage\n\n#### with the non-executable jar\n\n    java -cp target/json-hive-schema-1.0.jar net.thornydev.JsonHiveSchema file.json\n\n    # optionally specify the name of the table\n    java -cp target/json-hive-schema-1.0.jar net.thornydev.JsonHiveSchema file.json my_table_name\n\n\n#### with the executable jar\n\n    java -jar target/json-hive-schema-1.0-jar-with-dependencies.jar file.json\n\n    java -jar target/json-hive-schema-1.0-jar-with-dependencies.jar file.json my_table_name\n\n\nBoth print the Hive schema to stdout.\n\n\n#### Example:\n\nSuppose I have the JSON document:\n\n    {\n      \"description\": \"my doc\",\n      \"foo\": {\n        \"bar\": \"baz\",\n        \"quux\": \"revlos\",\n        \"level1\" : {\n          \"l2string\": \"l2val\",\n          \"l2struct\": {\n            \"level3\": \"l3val\"\n          }\n        }\n      },\n      \"wibble\": \"123\",\n      \"wobble\": [\n        {\n          \"entry\": 1,\n          \"EntryDetails\": {\n            \"details1\": \"lazybones\",\n            \"details2\": 414\n          }\n        },\n        {\n          \"entry\": 2,\n          \"EntryDetails\": {\n            \"details1\": \"entry 123\"\n          }\n        }\n      ]\n    }\n\n\nI recommend distilling it down to a doc with a single entry in each array and one that has all possible keys filled in - the values don't matter as long as they are present and a type can be determined.\n\nSo for the curated version of the JSON I've removed one of the entries from the \"wobble\" array and ensured that the remaining one has all the fields:\n\n    {\n      \"description\": \"my doc\",\n      \"foo\": {\n        \"bar\": \"baz\",\n        \"quux\": \"revlos\",\n        \"level1\" : {\n          \"l2string\": \"l2val\",\n          \"l2struct\": {\n            \"level3\": \"l3val\"\n          }\n        }\n      },\n      \"wibble\": \"123\",\n      \"wobble\": [\n        {\n          \"entry\": 1,\n          \"EntryDetails\": {\n            \"details1\": \"lazybones\",\n            \"details2\": 414\n          }\n        }\n      ]\n    }\n\n\n\nNow generate the schema:\n\n    $ java -jar target/json-hive-schema-1.0-jar-with-dependencies.jar in.json TopQuark\n    CREATE TABLE TopQuark (\n      description string,\n      foo struct<bar:string, level1:struct<l2string:string, l2struct:struct<level3:string>>, quux:string>,\n      wibble string,\n      wobble array<struct<entry:int, entrydetails:struct<details1:string, details2:int>>>)\n    ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe';\n\n\n\nYou can then load your data into Hive and run queries like this:\n\n    hive > select wobble.entry, wobble.EntryDetails.details1, wobble.EntryDetails[0].details2 from TopQuark;\n    entry   details1                    details2\n    [1,2]   [\"lazybones\",\"entry 123\"]   414\n    Time taken: 15.665 seconds\n"
  },
  {
    "path": "pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>net.thornydev</groupId>\n  <artifactId>json-hive-schema</artifactId>\n  <packaging>jar</packaging>\n  <version>1.0</version>\n  <name>json-hive-schema</name>\n  <url>http://maven.apache.org</url>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-compiler-plugin</artifactId>\n        <configuration>\n          <source>1.6</source>\n          <target>1.6</target>\n        </configuration>\n      </plugin>\n\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-jar-plugin</artifactId>\n        <version>2.4</version>\n      </plugin>\n\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-assembly-plugin</artifactId>\n        <version>2.4</version>\n        <configuration>\n          <descriptorRefs>\n            <descriptorRef>jar-with-dependencies</descriptorRef>\n          </descriptorRefs>\n          <archive>\n            <manifest>\n              <mainClass>net.thornydev.JsonHiveSchema</mainClass>\n            </manifest>\n          </archive>\n        </configuration>\n        <executions>\n          <execution>\n            <phase>package</phase>\n            <goals>\n              <goal>single</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "src/main/java/net/thornydev/JsonHiveSchema.java",
    "content": "package net.thornydev;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.util.Iterator;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\n\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\n/**\n * Generates Hive schemas for use with the JSON SerDe from\n * org.openx.data.jsonserde.JsonSerDe.  GitHub link: https://github.com/rcongiu/Hive-JSON-Serde\n * \n * Pass in a valid JSON document string to {@link JsonHiveSchema#createHiveSchema} and it will\n * return a Hive schema for the JSON document.\n * \n * It supports embedded JSON objects, arrays and the standard JSON scalar types: strings,\n * numbers, booleans and null.  You probably don't want null in the JSON document you provide\n * as Hive can't use that.  For numbers - if the example value has a decimal, it will be \n * typed as \"double\".  If the number has no decimal, it will be typed as \"int\".\n * \n * This program uses the JSON parsing code from json.org and that code is included in this\n * library, since it has not been packaged and made available for maven/ivy/gradle dependency\n * resolution.\n * \n * <strong>Use of main method:</strong> <br>\n *   JsonHiveSchema has a main method that takes a file path to a JSON doc - this file should have\n *   only one JSON file in it.  An optional second argument can be provided to name the Hive table\n *   that is generated.\n */\npublic class JsonHiveSchema  {\n  \n  static void help() {\n    System.out.println(\"Usage: Two arguments possible. First is required. Second is optional\");\n    System.out.println(\"  1st arg: path to JSON file to parse into Hive schema\");\n    System.out.println(\"  2nd arg (optional): tablename.  Defaults to 'x'\");\n  }\n  \n  public static void main( String[] args ) throws Exception {\n    if (args.length == 0) {\n      throw new IllegalArgumentException(\"ERROR: No file specified\");\n    }\n    \n    if (args[0].equals(\"-h\")) {\n      help();\n      System.exit(0);\n    }\n    \n    StringBuilder sb = new StringBuilder();\n    BufferedReader br = new BufferedReader( new FileReader(args[0]) );\n    String line;\n    while ( (line = br.readLine()) != null ) {\n      sb.append(line).append(\"\\n\");\n    }\n    br.close();\n    \n    String tableName = \"x\";\n    if (args.length == 2) {\n      tableName = args[1];\n    }\n\n    JsonHiveSchema schemaWriter = new JsonHiveSchema(tableName);\n    System.out.println(schemaWriter.createHiveSchema(sb.toString()));\n  }\n  \n  \n  private String tableName = \"x\";\n  \n  \n  public JsonHiveSchema() {}\n  \n  public JsonHiveSchema(String tableName) {\n    this.tableName = tableName;\n  }\n  \n  /**\n   * Pass in any valid JSON object and a Hive schema will be returned for it.\n   * You should avoid having null values in the JSON document, however.\n   * \n   * The Hive schema columns will be printed in alphabetical order - overall and\n   * within subsections.\n   * \n   * @param json\n   * @return string Hive schema\n   * @throws JSONException if the JSON does not parse correctly\n   */\n  public String createHiveSchema(String json) throws JSONException {\n    JSONObject jo = new JSONObject(json);\n    \n    @SuppressWarnings(\"unchecked\")\n    Iterator<String> keys = jo.keys();\n    keys = new OrderedIterator(keys);\n    StringBuilder sb = new StringBuilder(\"CREATE TABLE \").append(tableName).append(\" (\\n\");\n\n    while (keys.hasNext()) {\n      String k = keys.next();\n      sb.append(\"  \");\n      sb.append(k.toString());\n      sb.append(' ');\n      sb.append(valueToHiveSchema(jo.opt(k)));\n      sb.append(',').append(\"\\n\");\n    }\n\n    sb.replace(sb.length() - 2, sb.length(), \")\\n\"); // remove last comma\n    return sb.append(\"ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe';\").toString();\n  }\n\n  private String toHiveSchema(JSONObject o) throws JSONException { \n    @SuppressWarnings(\"unchecked\")\n    Iterator<String> keys = o.keys();\n    keys = new OrderedIterator(keys);\n    StringBuilder sb = new StringBuilder(\"struct<\");\n    \n    while (keys.hasNext()) {\n      String k = keys.next();\n      sb.append(k.toString());\n      sb.append(':');\n      sb.append(valueToHiveSchema(o.opt(k)));\n      sb.append(\", \");\n    }\n    sb.replace(sb.length() - 2, sb.length(), \">\"); // remove last comma\n    return sb.toString();\n  }\n\n  private String toHiveSchema(JSONArray a) throws JSONException {\n    return \"array<\" + arrayJoin(a, \",\") + '>';\n  }\n\n  private String arrayJoin(JSONArray a, String separator) throws JSONException {\n    StringBuilder sb = new StringBuilder();\n\n    if (a.length() == 0) {\n      throw new IllegalStateException(\"Array is empty: \" + a.toString());\n    }\n    \n    Object entry0 = a.get(0);\n    if ( isScalar(entry0) ) {\n      sb.append( scalarType(entry0) );\n    } else if (entry0 instanceof JSONObject) {\n      sb.append( toHiveSchema((JSONObject)entry0) );\n    } else if (entry0 instanceof JSONArray) {    \n      sb.append( toHiveSchema((JSONArray)entry0) );\n    }\n    return sb.toString();\n  }\n  \n  private String scalarType(Object o) {\n    if (o instanceof String) return \"string\";\n    if (o instanceof Number) return scalarNumericType(o);\n    if (o instanceof Boolean) return \"boolean\";\n    return null;\n  }\n\n  private String scalarNumericType(Object o) {\n    String s = o.toString();\n    if (s.indexOf('.') > 0) {\n      return \"double\";\n    } else {\n      return \"int\";\n    }\n  }\n\n  private boolean isScalar(Object o) {\n    return o instanceof String ||\n        o instanceof Number ||\n        o instanceof Boolean || \n        o == JSONObject.NULL;\n  }\n\n  private String valueToHiveSchema(Object o) throws JSONException {\n    if ( isScalar(o) ) {\n      return scalarType(o);\n    } else if (o instanceof JSONObject) {\n      return toHiveSchema((JSONObject)o);\n    } else if (o instanceof JSONArray) {\n      return toHiveSchema((JSONArray)o);\n    } else {\n      throw new IllegalArgumentException(\"unknown type: \" + o.getClass());\n    }\n  }\n  \n  static class OrderedIterator implements Iterator<String> {\n\n    Iterator<String> it;\n    \n    public OrderedIterator(Iterator<String> iter) {\n      SortedSet<String> keys = new TreeSet<String>();\n      while (iter.hasNext()) {\n        keys.add(iter.next());\n      }\n      it = keys.iterator();\n    }\n    \n    public boolean hasNext() {\n      return it.hasNext();\n    }\n\n    public String next() {\n      return it.next();\n    }\n\n    public void remove() {\n      it.remove();\n    }\n  }\n}\n"
  },
  {
    "path": "src/main/java/org/json/JSONArray.java",
    "content": "package org.json;\n\n/*\nCopyright (c) 2002 JSON.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nThe Software shall be used for Good, not Evil.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.Map;\n\n/**\n * A JSONArray is an ordered sequence of values. Its external text form is a\n * string wrapped in square brackets with commas separating the values. The\n * internal form is an object having <code>get</code> and <code>opt</code>\n * methods for accessing the values by index, and <code>put</code> methods for\n * adding or replacing values. The values can be any of these types:\n * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,\n * <code>Number</code>, <code>String</code>, or the\n * <code>JSONObject.NULL object</code>.\n * <p>\n * The constructor can convert a JSON text into a Java object. The\n * <code>toString</code> method converts to JSON text.\n * <p>\n * A <code>get</code> method returns a value if one can be found, and throws an\n * exception if one cannot be found. An <code>opt</code> method returns a\n * default value instead of throwing an exception, and so is useful for\n * obtaining optional values.\n * <p>\n * The generic <code>get()</code> and <code>opt()</code> methods return an\n * object which you can cast or query for type. There are also typed\n * <code>get</code> and <code>opt</code> methods that do type checking and type\n * coercion for you.\n * <p>\n * The texts produced by the <code>toString</code> methods strictly conform to\n * JSON syntax rules. The constructors are more forgiving in the texts they will\n * accept:\n * <ul>\n * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just\n *     before the closing bracket.</li>\n * <li>The <code>null</code> value will be inserted when there\n *     is <code>,</code>&nbsp;<small>(comma)</small> elision.</li>\n * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single\n *     quote)</small>.</li>\n * <li>Strings do not need to be quoted at all if they do not begin with a quote\n *     or single quote, and if they do not contain leading or trailing spaces,\n *     and if they do not contain any of these characters:\n *     <code>{ } [ ] / \\ : , = ; #</code> and if they do not look like numbers\n *     and if they are not the reserved words <code>true</code>,\n *     <code>false</code>, or <code>null</code>.</li>\n * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as\n *     well as by <code>,</code> <small>(comma)</small>.</li>\n * <li>Numbers may have the \n *     <code>0x-</code> <small>(hex)</small> prefix.</li>\n * </ul>\n\n * @author JSON.org\n * @version 2011-05-04\n */\npublic class JSONArray {\n\n\n    /**\n     * The arrayList where the JSONArray's properties are kept.\n     */\n    private ArrayList myArrayList;\n\n\n    /**\n     * Construct an empty JSONArray.\n     */\n    public JSONArray() {\n        this.myArrayList = new ArrayList();\n    }\n\n    /**\n     * Construct a JSONArray from a JSONTokener.\n     * @param x A JSONTokener\n     * @throws JSONException If there is a syntax error.\n     */\n    public JSONArray(JSONTokener x) throws JSONException {\n        this();\n        if (x.nextClean() != '[') {\n            throw x.syntaxError(\"A JSONArray text must start with '['\");\n        }\n        if (x.nextClean() != ']') {\n\t        x.back();\n\t        for (;;) {\n\t            if (x.nextClean() == ',') {\n\t                x.back();\n\t                this.myArrayList.add(JSONObject.NULL);\n\t            } else {\n\t                x.back();\n\t                this.myArrayList.add(x.nextValue());\n\t            }\n\t            switch (x.nextClean()) {\n\t            case ';':\n\t            case ',':\n\t                if (x.nextClean() == ']') {\n\t                    return;\n\t                }\n\t                x.back();\n\t                break;\n\t            case ']':\n\t            \treturn;\n\t            default:\n\t                throw x.syntaxError(\"Expected a ',' or ']'\");\n\t            }\n\t        }\n        }\n    }\n\n\n    /**\n     * Construct a JSONArray from a source JSON text.\n     * @param source     A string that begins with\n     * <code>[</code>&nbsp;<small>(left bracket)</small>\n     *  and ends with <code>]</code>&nbsp;<small>(right bracket)</small>.\n     *  @throws JSONException If there is a syntax error.\n     */\n    public JSONArray(String source) throws JSONException {\n        this(new JSONTokener(source));\n    }\n\n\n    /**\n     * Construct a JSONArray from a Collection.\n     * @param collection     A Collection.\n     */\n    public JSONArray(Collection collection) {\n\t\tthis.myArrayList = new ArrayList();\n\t\tif (collection != null) {\n\t\t\tIterator iter = collection.iterator();\n\t\t\twhile (iter.hasNext()) {\n                this.myArrayList.add(JSONObject.wrap(iter.next()));  \n\t\t\t}\n\t\t}\n    }\n\n    \n    /**\n     * Construct a JSONArray from an array\n     * @throws JSONException If not an array.\n     */\n    public JSONArray(Object array) throws JSONException {\n        this();\n        if (array.getClass().isArray()) {\n            int length = Array.getLength(array);\n            for (int i = 0; i < length; i += 1) {\n                this.put(JSONObject.wrap(Array.get(array, i)));\n            }\n        } else {\n            throw new JSONException(\n\"JSONArray initial value should be a string or collection or array.\");\n        }\n    }\n    \n    \n    /**\n     * Get the object value associated with an index.\n     * @param index\n     *  The index must be between 0 and length() - 1.\n     * @return An object value.\n     * @throws JSONException If there is no value for the index.\n     */\n    public Object get(int index) throws JSONException {\n        Object object = opt(index);\n        if (object == null) {\n            throw new JSONException(\"JSONArray[\" + index + \"] not found.\");\n        }\n        return object;\n    }\n\n\n    /**\n     * Get the boolean value associated with an index.\n     * The string values \"true\" and \"false\" are converted to boolean.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      The truth.\n     * @throws JSONException If there is no value for the index or if the\n     *  value is not convertible to boolean.\n     */\n    public boolean getBoolean(int index) throws JSONException {\n        Object object = get(index);\n        if (object.equals(Boolean.FALSE) ||\n                (object instanceof String &&\n                ((String)object).equalsIgnoreCase(\"false\"))) {\n            return false;\n        } else if (object.equals(Boolean.TRUE) ||\n                (object instanceof String &&\n                ((String)object).equalsIgnoreCase(\"true\"))) {\n            return true;\n        }\n        throw new JSONException(\"JSONArray[\" + index + \"] is not a boolean.\");\n    }\n\n\n    /**\n     * Get the double value associated with an index.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      The value.\n     * @throws   JSONException If the key is not found or if the value cannot\n     *  be converted to a number.\n     */\n    public double getDouble(int index) throws JSONException {\n        Object object = get(index);\n        try {\n            return object instanceof Number ?\n                ((Number)object).doubleValue() :\n                Double.parseDouble((String)object);\n        } catch (Exception e) {\n            throw new JSONException(\"JSONArray[\" + index +\n                \"] is not a number.\");\n        }\n    }\n\n\n    /**\n     * Get the int value associated with an index.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      The value.\n     * @throws   JSONException If the key is not found or if the value is not a number.\n     */\n    public int getInt(int index) throws JSONException {\n        Object object = get(index);\n        try {\n            return object instanceof Number ?\n                ((Number)object).intValue() :\n                Integer.parseInt((String)object);\n        } catch (Exception e) {\n            throw new JSONException(\"JSONArray[\" + index +\n                \"] is not a number.\");\n        }\n    }\n\n\n    /**\n     * Get the JSONArray associated with an index.\n     * @param index The index must be between 0 and length() - 1.\n     * @return      A JSONArray value.\n     * @throws JSONException If there is no value for the index. or if the\n     * value is not a JSONArray\n     */\n    public JSONArray getJSONArray(int index) throws JSONException {\n        Object object = get(index);\n        if (object instanceof JSONArray) {\n            return (JSONArray)object;\n        }\n        throw new JSONException(\"JSONArray[\" + index +\n                \"] is not a JSONArray.\");\n    }\n\n\n    /**\n     * Get the JSONObject associated with an index.\n     * @param index subscript\n     * @return      A JSONObject value.\n     * @throws JSONException If there is no value for the index or if the\n     * value is not a JSONObject\n     */\n    public JSONObject getJSONObject(int index) throws JSONException {\n        Object object = get(index);\n        if (object instanceof JSONObject) {\n            return (JSONObject)object;\n        }\n        throw new JSONException(\"JSONArray[\" + index +\n            \"] is not a JSONObject.\");\n    }\n\n\n    /**\n     * Get the long value associated with an index.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      The value.\n     * @throws   JSONException If the key is not found or if the value cannot\n     *  be converted to a number.\n     */\n    public long getLong(int index) throws JSONException {\n        Object object = get(index);\n        try {\n            return object instanceof Number ?\n                ((Number)object).longValue() :\n                Long.parseLong((String)object);\n        } catch (Exception e) {\n            throw new JSONException(\"JSONArray[\" + index +\n                \"] is not a number.\");\n        }\n    }\n\n\n    /**\n     * Get the string associated with an index.\n     * @param index The index must be between 0 and length() - 1.\n     * @return      A string value.\n     * @throws JSONException If there is no string value for the index.\n     */\n    public String getString(int index) throws JSONException {\n        Object object = get(index);\n        if (object instanceof String) {\n            return (String)object;\n        }\n        throw new JSONException(\"JSONArray[\" + index + \"] not a string.\");\n    }\n\n\n    /**\n     * Determine if the value is null.\n     * @param index The index must be between 0 and length() - 1.\n     * @return true if the value at the index is null, or if there is no value.\n     */\n    public boolean isNull(int index) {\n        return JSONObject.NULL.equals(opt(index));\n    }\n\n\n    /**\n     * Make a string from the contents of this JSONArray. The\n     * <code>separator</code> string is inserted between each element.\n     * Warning: This method assumes that the data structure is acyclical.\n     * @param separator A string that will be inserted between the elements.\n     * @return a string.\n     * @throws JSONException If the array contains an invalid number.\n     */\n    public String join(String separator) throws JSONException {\n        int len = length();\n        StringBuffer sb = new StringBuffer();\n\n        for (int i = 0; i < len; i += 1) {\n            if (i > 0) {\n                sb.append(separator);\n            }\n            sb.append(JSONObject.valueToString(this.myArrayList.get(i)));\n        }\n        return sb.toString();\n    }\n\n\n    /**\n     * Get the number of elements in the JSONArray, included nulls.\n     *\n     * @return The length (or size).\n     */\n    public int length() {\n        return this.myArrayList.size();\n    }\n\n\n    /**\n     * Get the optional object value associated with an index.\n     * @param index The index must be between 0 and length() - 1.\n     * @return      An object value, or null if there is no\n     *              object at that index.\n     */\n    public Object opt(int index) {\n        return (index < 0 || index >= length()) ?\n            null : this.myArrayList.get(index);\n    }\n\n\n    /**\n     * Get the optional boolean value associated with an index.\n     * It returns false if there is no value at that index,\n     * or if the value is not Boolean.TRUE or the String \"true\".\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      The truth.\n     */\n    public boolean optBoolean(int index)  {\n        return optBoolean(index, false);\n    }\n\n\n    /**\n     * Get the optional boolean value associated with an index.\n     * It returns the defaultValue if there is no value at that index or if\n     * it is not a Boolean or the String \"true\" or \"false\" (case insensitive).\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @param defaultValue     A boolean default.\n     * @return      The truth.\n     */\n    public boolean optBoolean(int index, boolean defaultValue)  {\n        try {\n            return getBoolean(index);\n        } catch (Exception e) {\n            return defaultValue;\n        }\n    }\n\n\n    /**\n     * Get the optional double value associated with an index.\n     * NaN is returned if there is no value for the index,\n     * or if the value is not a number and cannot be converted to a number.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      The value.\n     */\n    public double optDouble(int index) {\n        return optDouble(index, Double.NaN);\n    }\n\n\n    /**\n     * Get the optional double value associated with an index.\n     * The defaultValue is returned if there is no value for the index,\n     * or if the value is not a number and cannot be converted to a number.\n     *\n     * @param index subscript\n     * @param defaultValue     The default value.\n     * @return      The value.\n     */\n    public double optDouble(int index, double defaultValue) {\n        try {\n            return getDouble(index);\n        } catch (Exception e) {\n            return defaultValue;\n        }\n    }\n\n\n    /**\n     * Get the optional int value associated with an index.\n     * Zero is returned if there is no value for the index,\n     * or if the value is not a number and cannot be converted to a number.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      The value.\n     */\n    public int optInt(int index) {\n        return optInt(index, 0);\n    }\n\n\n    /**\n     * Get the optional int value associated with an index.\n     * The defaultValue is returned if there is no value for the index,\n     * or if the value is not a number and cannot be converted to a number.\n     * @param index The index must be between 0 and length() - 1.\n     * @param defaultValue     The default value.\n     * @return      The value.\n     */\n    public int optInt(int index, int defaultValue) {\n        try {\n            return getInt(index);\n        } catch (Exception e) {\n            return defaultValue;\n        }\n    }\n\n\n    /**\n     * Get the optional JSONArray associated with an index.\n     * @param index subscript\n     * @return      A JSONArray value, or null if the index has no value,\n     * or if the value is not a JSONArray.\n     */\n    public JSONArray optJSONArray(int index) {\n        Object o = opt(index);\n        return o instanceof JSONArray ? (JSONArray)o : null;\n    }\n\n\n    /**\n     * Get the optional JSONObject associated with an index.\n     * Null is returned if the key is not found, or null if the index has\n     * no value, or if the value is not a JSONObject.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      A JSONObject value.\n     */\n    public JSONObject optJSONObject(int index) {\n        Object o = opt(index);\n        return o instanceof JSONObject ? (JSONObject)o : null;\n    }\n\n\n    /**\n     * Get the optional long value associated with an index.\n     * Zero is returned if there is no value for the index,\n     * or if the value is not a number and cannot be converted to a number.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      The value.\n     */\n    public long optLong(int index) {\n        return optLong(index, 0);\n    }\n\n\n    /**\n     * Get the optional long value associated with an index.\n     * The defaultValue is returned if there is no value for the index,\n     * or if the value is not a number and cannot be converted to a number.\n     * @param index The index must be between 0 and length() - 1.\n     * @param defaultValue     The default value.\n     * @return      The value.\n     */\n    public long optLong(int index, long defaultValue) {\n        try {\n            return getLong(index);\n        } catch (Exception e) {\n            return defaultValue;\n        }\n    }\n\n\n    /**\n     * Get the optional string value associated with an index. It returns an\n     * empty string if there is no value at that index. If the value\n     * is not a string and is not null, then it is coverted to a string.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @return      A String value.\n     */\n    public String optString(int index) {\n        return optString(index, \"\");\n    }\n\n\n    /**\n     * Get the optional string associated with an index.\n     * The defaultValue is returned if the key is not found.\n     *\n     * @param index The index must be between 0 and length() - 1.\n     * @param defaultValue     The default value.\n     * @return      A String value.\n     */\n    public String optString(int index, String defaultValue) {\n        Object object = opt(index);\n        return object != null ? object.toString() : defaultValue;\n    }\n\n\n    /**\n     * Append a boolean value. This increases the array's length by one.\n     *\n     * @param value A boolean value.\n     * @return this.\n     */\n    public JSONArray put(boolean value) {\n        put(value ? Boolean.TRUE : Boolean.FALSE);\n        return this;\n    }\n\n\n    /**\n     * Put a value in the JSONArray, where the value will be a\n     * JSONArray which is produced from a Collection.\n     * @param value A Collection value.\n     * @return      this.\n     */\n    public JSONArray put(Collection value) {\n        put(new JSONArray(value));\n        return this;\n    }\n\n\n    /**\n     * Append a double value. This increases the array's length by one.\n     *\n     * @param value A double value.\n     * @throws JSONException if the value is not finite.\n     * @return this.\n     */\n    public JSONArray put(double value) throws JSONException {\n        Double d = new Double(value);\n        JSONObject.testValidity(d);\n        put(d);\n        return this;\n    }\n\n\n    /**\n     * Append an int value. This increases the array's length by one.\n     *\n     * @param value An int value.\n     * @return this.\n     */\n    public JSONArray put(int value) {\n        put(new Integer(value));\n        return this;\n    }\n\n\n    /**\n     * Append an long value. This increases the array's length by one.\n     *\n     * @param value A long value.\n     * @return this.\n     */\n    public JSONArray put(long value) {\n        put(new Long(value));\n        return this;\n    }\n\n\n    /**\n     * Put a value in the JSONArray, where the value will be a\n     * JSONObject which is produced from a Map.\n     * @param value A Map value.\n     * @return      this.\n     */\n    public JSONArray put(Map value) {\n        put(new JSONObject(value));\n        return this;\n    }\n\n\n    /**\n     * Append an object value. This increases the array's length by one.\n     * @param value An object value.  The value should be a\n     *  Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the\n     *  JSONObject.NULL object.\n     * @return this.\n     */\n    public JSONArray put(Object value) {\n        this.myArrayList.add(value);\n        return this;\n    }\n\n\n    /**\n     * Put or replace a boolean value in the JSONArray. If the index is greater\n     * than the length of the JSONArray, then null elements will be added as\n     * necessary to pad it out.\n     * @param index The subscript.\n     * @param value A boolean value.\n     * @return this.\n     * @throws JSONException If the index is negative.\n     */\n    public JSONArray put(int index, boolean value) throws JSONException {\n        put(index, value ? Boolean.TRUE : Boolean.FALSE);\n        return this;\n    }\n\n\n    /**\n     * Put a value in the JSONArray, where the value will be a\n     * JSONArray which is produced from a Collection.\n     * @param index The subscript.\n     * @param value A Collection value.\n     * @return      this.\n     * @throws JSONException If the index is negative or if the value is\n     * not finite.\n     */\n    public JSONArray put(int index, Collection value) throws JSONException {\n        put(index, new JSONArray(value));\n        return this;\n    }\n\n\n    /**\n     * Put or replace a double value. If the index is greater than the length of\n     *  the JSONArray, then null elements will be added as necessary to pad\n     *  it out.\n     * @param index The subscript.\n     * @param value A double value.\n     * @return this.\n     * @throws JSONException If the index is negative or if the value is\n     * not finite.\n     */\n    public JSONArray put(int index, double value) throws JSONException {\n        put(index, new Double(value));\n        return this;\n    }\n\n\n    /**\n     * Put or replace an int value. If the index is greater than the length of\n     *  the JSONArray, then null elements will be added as necessary to pad\n     *  it out.\n     * @param index The subscript.\n     * @param value An int value.\n     * @return this.\n     * @throws JSONException If the index is negative.\n     */\n    public JSONArray put(int index, int value) throws JSONException {\n        put(index, new Integer(value));\n        return this;\n    }\n\n\n    /**\n     * Put or replace a long value. If the index is greater than the length of\n     *  the JSONArray, then null elements will be added as necessary to pad\n     *  it out.\n     * @param index The subscript.\n     * @param value A long value.\n     * @return this.\n     * @throws JSONException If the index is negative.\n     */\n    public JSONArray put(int index, long value) throws JSONException {\n        put(index, new Long(value));\n        return this;\n    }\n\n\n    /**\n     * Put a value in the JSONArray, where the value will be a\n     * JSONObject that is produced from a Map.\n     * @param index The subscript.\n     * @param value The Map value.\n     * @return      this.\n     * @throws JSONException If the index is negative or if the the value is\n     *  an invalid number.\n     */\n    public JSONArray put(int index, Map value) throws JSONException {\n        put(index, new JSONObject(value));\n        return this;\n    }\n\n\n    /**\n     * Put or replace an object value in the JSONArray. If the index is greater\n     *  than the length of the JSONArray, then null elements will be added as\n     *  necessary to pad it out.\n     * @param index The subscript.\n     * @param value The value to put into the array. The value should be a\n     *  Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the\n     *  JSONObject.NULL object.\n     * @return this.\n     * @throws JSONException If the index is negative or if the the value is\n     *  an invalid number.\n     */\n    public JSONArray put(int index, Object value) throws JSONException {\n        JSONObject.testValidity(value);\n        if (index < 0) {\n            throw new JSONException(\"JSONArray[\" + index + \"] not found.\");\n        }\n        if (index < length()) {\n            this.myArrayList.set(index, value);\n        } else {\n            while (index != length()) {\n                put(JSONObject.NULL);\n            }\n            put(value);\n        }\n        return this;\n    }\n    \n    \n    /**\n     * Remove an index and close the hole.\n     * @param index The index of the element to be removed.\n     * @return The value that was associated with the index,\n     * or null if there was no value.\n     */\n    public Object remove(int index) {\n    \tObject o = opt(index);\n        this.myArrayList.remove(index);\n        return o;\n    }\n\n\n    /**\n     * Produce a JSONObject by combining a JSONArray of names with the values\n     * of this JSONArray.\n     * @param names A JSONArray containing a list of key strings. These will be\n     * paired with the values.\n     * @return A JSONObject, or null if there are no names or if this JSONArray\n     * has no values.\n     * @throws JSONException If any of the names are null.\n     */\n    public JSONObject toJSONObject(JSONArray names) throws JSONException {\n        if (names == null || names.length() == 0 || length() == 0) {\n            return null;\n        }\n        JSONObject jo = new JSONObject();\n        for (int i = 0; i < names.length(); i += 1) {\n            jo.put(names.getString(i), this.opt(i));\n        }\n        return jo;\n    }\n\n\n    /**\n     * Make a JSON text of this JSONArray. For compactness, no\n     * unnecessary whitespace is added. If it is not possible to produce a\n     * syntactically correct JSON text then null will be returned instead. This\n     * could occur if the array contains an invalid number.\n     * <p>\n     * Warning: This method assumes that the data structure is acyclical.\n     *\n     * @return a printable, displayable, transmittable\n     *  representation of the array.\n     */\n    @Override\n    public String toString() {\n        try {\n            return '[' + join(\",\") + ']';\n        } catch (Exception e) {\n            return null;\n        }\n    }\n\n\n    /**\n     * Make a prettyprinted JSON text of this JSONArray.\n     * Warning: This method assumes that the data structure is acyclical.\n     * @param indentFactor The number of spaces to add to each level of\n     *  indentation.\n     * @return a printable, displayable, transmittable\n     *  representation of the object, beginning\n     *  with <code>[</code>&nbsp;<small>(left bracket)</small> and ending\n     *  with <code>]</code>&nbsp;<small>(right bracket)</small>.\n     * @throws JSONException\n     */\n    public String toString(int indentFactor) throws JSONException {\n        return toString(indentFactor, 0);\n    }\n\n\n    /**\n     * Make a prettyprinted JSON text of this JSONArray.\n     * Warning: This method assumes that the data structure is acyclical.\n     * @param indentFactor The number of spaces to add to each level of\n     *  indentation.\n     * @param indent The indention of the top level.\n     * @return a printable, displayable, transmittable\n     *  representation of the array.\n     * @throws JSONException\n     */\n    String toString(int indentFactor, int indent) throws JSONException {\n        int len = length();\n        if (len == 0) {\n            return \"[]\";\n        }\n        int i;\n        StringBuffer sb = new StringBuffer(\"[\");\n        if (len == 1) {\n            sb.append(JSONObject.valueToString(this.myArrayList.get(0),\n                    indentFactor, indent));\n        } else {\n            int newindent = indent + indentFactor;\n            sb.append('\\n');\n            for (i = 0; i < len; i += 1) {\n                if (i > 0) {\n                    sb.append(\",\\n\");\n                }\n                for (int j = 0; j < newindent; j += 1) {\n                    sb.append(' ');\n                }\n                sb.append(JSONObject.valueToString(this.myArrayList.get(i),\n                        indentFactor, newindent));\n            }\n            sb.append('\\n');\n            for (i = 0; i < indent; i += 1) {\n                sb.append(' ');\n            }\n        }\n        sb.append(']');\n        return sb.toString();\n    }\n\n\n    /**\n     * Write the contents of the JSONArray as JSON text to a writer.\n     * For compactness, no whitespace is added.\n     * <p>\n     * Warning: This method assumes that the data structure is acyclical.\n     *\n     * @return The writer.\n     * @throws JSONException\n     */\n    public Writer write(Writer writer) throws JSONException {\n        try {\n            boolean b = false;\n            int     len = length();\n\n            writer.write('[');\n\n            for (int i = 0; i < len; i += 1) {\n                if (b) {\n                    writer.write(',');\n                }\n                Object v = this.myArrayList.get(i);\n                if (v instanceof JSONObject) {\n                    ((JSONObject)v).write(writer);\n                } else if (v instanceof JSONArray) {\n                    ((JSONArray)v).write(writer);\n                } else {\n                    writer.write(JSONObject.valueToString(v));\n                }\n                b = true;\n            }\n            writer.write(']');\n            return writer;\n        } catch (IOException e) {\n           throw new JSONException(e);\n        }\n    }\n\n    public ArrayList getAsArrayList() {\n        return myArrayList;\n    }\n    \n    \n    \n    \n}"
  },
  {
    "path": "src/main/java/org/json/JSONException.java",
    "content": "package org.json;\r\n\r\n/**\r\n * The JSONException is thrown by the JSON.org classes when things are amiss.\r\n * @author JSON.org\r\n * @version 2010-12-24\r\n */\r\npublic class JSONException extends Exception {\r\n\tprivate static final long serialVersionUID = 0;\r\n\tprivate Throwable cause;\r\n\r\n    /**\r\n     * Constructs a JSONException with an explanatory message.\r\n     * @param message Detail about the reason for the exception.\r\n     */\r\n    public JSONException(String message) {\r\n        super(message);\r\n    }\r\n\r\n    public JSONException(Throwable cause) {\r\n        super(cause.getMessage());\r\n        this.cause = cause;\r\n    }\r\n\r\n    public Throwable getCause() {\r\n        return this.cause;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/main/java/org/json/JSONObject.java",
    "content": "package org.json;\n\n/*\nCopyright (c) 2002 JSON.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nThe Software shall be used for Good, not Evil.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.ResourceBundle;\n\n/**\n * A JSONObject is an unordered collection of name/value pairs. Its\n * external form is a string wrapped in curly braces with colons between the\n * names and values, and commas between the values and names. The internal form\n * is an object having <code>get</code> and <code>opt</code> methods for\n * accessing the values by name, and <code>put</code> methods for adding or\n * replacing values by name. The values can be any of these types:\n * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,\n * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code>\n * object. A JSONObject constructor can be used to convert an external form\n * JSON text into an internal form whose values can be retrieved with the\n * <code>get</code> and <code>opt</code> methods, or to convert values into a\n * JSON text using the <code>put</code> and <code>toString</code> methods.\n * A <code>get</code> method returns a value if one can be found, and throws an\n * exception if one cannot be found. An <code>opt</code> method returns a\n * default value instead of throwing an exception, and so is useful for\n * obtaining optional values.\n * <p>\n * The generic <code>get()</code> and <code>opt()</code> methods return an\n * object, which you can cast or query for type. There are also typed\n * <code>get</code> and <code>opt</code> methods that do type checking and type\n * coercion for you. The opt methods differ from the get methods in that they\n * do not throw. Instead, they return a specified value, such as null.\n * <p>\n * The <code>put</code> methods add or replace values in an object. For example, \n * <pre>myString = new JSONObject().put(\"JSON\", \"Hello, World!\").toString();</pre>\n * produces the string <code>{\"JSON\": \"Hello, World\"}</code>.\n * <p>\n * The texts produced by the <code>toString</code> methods strictly conform to\n * the JSON syntax rules.\n * The constructors are more forgiving in the texts they will accept:\n * <ul>\n * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just\n *     before the closing brace.</li>\n * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single\n *     quote)</small>.</li>\n * <li>Strings do not need to be quoted at all if they do not begin with a quote\n *     or single quote, and if they do not contain leading or trailing spaces,\n *     and if they do not contain any of these characters:\n *     <code>{ } [ ] / \\ : , = ; #</code> and if they do not look like numbers\n *     and if they are not the reserved words <code>true</code>,\n *     <code>false</code>, or <code>null</code>.</li>\n * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as\n *     by <code>:</code>.</li>\n * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as\n *     well as by <code>,</code> <small>(comma)</small>.</li>\n * <li>Numbers may have the <code>0x-</code> <small>(hex)</small> prefix.</li>\n * </ul>\n * @author JSON.org\n * @version 2011-04-05\n */\npublic class JSONObject {\n\n    /**\n     * JSONObject.NULL is equivalent to the value that JavaScript calls null,\n     * whilst Java's null is equivalent to the value that JavaScript calls\n     * undefined.\n     */\n     private static final class Null {\n\n        /**\n         * There is only intended to be a single instance of the NULL object,\n         * so the clone method returns itself.\n         * @return     NULL.\n         */\n        protected final Object clone() {\n            return this;\n        }\n\n        /**\n         * A Null object is equal to the null value and to itself.\n         * @param object    An object to test for nullness.\n         * @return true if the object parameter is the JSONObject.NULL object\n         *  or null.\n         */\n        @Override\n        public boolean equals(Object object) {\n            if(! (object instanceof JSONObject)) {\n                return false;\n            } else {\n                return object == null || object == this;\n            }\n        }\n\n        /**\n         * Get the \"null\" string value.\n         * @return The string \"null\".\n         */\n        @Override\n        public String toString() {\n            return \"null\";\n        }\n\n        @Override\n        public int hashCode() {\n            int hash = 3;\n            return hash;\n        }\n    }\n\n\n    /**\n     * The map where the JSONObject's properties are kept.\n     */\n    private Map map;\n\n\n    /**\n     * It is sometimes more convenient and less ambiguous to have a\n     * <code>NULL</code> object than to use Java's <code>null</code> value.\n     * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.\n     * <code>JSONObject.NULL.toString()</code> returns <code>\"null\"</code>.\n     */\n    public static final Object NULL = new Null();\n\n\n    /**\n     * Construct an empty JSONObject.\n     */\n    public JSONObject() {\n        this.map = new HashMap();\n    }\n\n\n    /**\n     * Construct a JSONObject from a subset of another JSONObject.\n     * An array of strings is used to identify the keys that should be copied.\n     * Missing keys are ignored.\n     * @param jo A JSONObject.\n     * @param names An array of strings.\n     * @throws JSONException \n     * @exception JSONException If a value is a non-finite number or if a name is duplicated.\n     */\n    public JSONObject(JSONObject jo, String[] names) {\n        this();\n        for (int i = 0; i < names.length; i += 1) {\n            try {\n                putOnce(names[i].toLowerCase(), jo.opt(names[i]));\n            } catch (Exception ignore) {\n            }\n        }\n    }\n\n\n    /**\n     * Construct a JSONObject from a JSONTokener.\n     * @param x A JSONTokener object containing the source string.\n     * @throws JSONException If there is a syntax error in the source string\n     *  or a duplicated key.\n     */\n    public JSONObject(JSONTokener x) throws JSONException {\n        this();\n        char c;\n        String key;\n\n        if (x.nextClean() != '{') {\n            throw x.syntaxError(\"A JSONObject text must begin with '{'\");\n        }\n        for (;;) {\n            c = x.nextClean();\n            switch (c) {\n            case 0:\n                throw x.syntaxError(\"A JSONObject text must end with '}'\");\n            case '}':\n                return;\n            default:\n                x.back();\n                key = x.nextValue().toString().toLowerCase();\n            }\n\n// The key is followed by ':'. We will also tolerate '=' or '=>'.\n\n            c = x.nextClean();\n            if (c == '=') {\n                if (x.next() != '>') {\n                    x.back();\n                }\n            } else if (c != ':') {\n                throw x.syntaxError(\"Expected a ':' after a key\");\n            }\n            putOnce(key, x.nextValue());\n\n// Pairs are separated by ','. We will also tolerate ';'.\n\n            switch (x.nextClean()) {\n            case ';':\n            case ',':\n                if (x.nextClean() == '}') {\n                    return;\n                }\n                x.back();\n                break;\n            case '}':\n                return;\n            default:\n                throw x.syntaxError(\"Expected a ',' or '}'\");\n            }\n        }\n    }\n\n\n    /**\n     * Construct a JSONObject from a Map.\n     *\n     * @param map A map object that can be used to initialize the contents of\n     *  the JSONObject.\n     * @throws JSONException \n     */\n    public JSONObject(Map map) {\n        this.map = new HashMap();\n        if (map != null) {\n            Iterator i = map.entrySet().iterator();\n            while (i.hasNext()) {\n                Map.Entry e = (Map.Entry)i.next();\n                Object value = e.getValue();\n                if (value != null) {\n                    this.map.put(e.getKey(), wrap(value));\n                }\n            }\n        }\n    }\n\n\n    /**\n     * Construct a JSONObject from an Object using bean getters.\n     * It reflects on all of the public methods of the object.\n     * For each of the methods with no parameters and a name starting\n     * with <code>\"get\"</code> or <code>\"is\"</code> followed by an uppercase letter,\n     * the method is invoked, and a key and the value returned from the getter method\n     * are put into the new JSONObject.\n     *\n     * The key is formed by removing the <code>\"get\"</code> or <code>\"is\"</code> prefix.\n     * If the second remaining character is not upper case, then the first\n     * character is converted to lower case.\n     *\n     * For example, if an object has a method named <code>\"getName\"</code>, and\n     * if the result of calling <code>object.getName()</code> is <code>\"Larry Fine\"</code>,\n     * then the JSONObject will contain <code>\"name\": \"Larry Fine\"</code>.\n     *\n     * @param bean An object that has getter methods that should be used\n     * to make a JSONObject.\n     */\n    public JSONObject(Object bean) {\n        this();\n        populateMap(bean);\n    }\n\n\n    /**\n     * Construct a JSONObject from an Object, using reflection to find the\n     * public members. The resulting JSONObject's keys will be the strings\n     * from the names array, and the values will be the field values associated\n     * with those keys in the object. If a key is not found or not visible,\n     * then it will not be copied into the new JSONObject.\n     * @param object An object that has fields that should be used to make a\n     * JSONObject.\n     * @param names An array of strings, the names of the fields to be obtained\n     * from the object.\n     */\n    public JSONObject(Object object, String names[]) {\n        this();\n        Class c = object.getClass();\n        for (int i = 0; i < names.length; i += 1) {\n            String name = names[i];\n            try {\n                putOpt(name.toLowerCase(), c.getField(name).get(object));\n            } catch (Exception ignore) {\n            }\n        }\n    }\n\n\n    /**\n     * Construct a JSONObject from a source JSON text string.\n     * This is the most commonly used JSONObject constructor.\n     * @param source    A string beginning\n     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending\n     *  with <code>}</code>&nbsp;<small>(right brace)</small>.\n     * @exception JSONException If there is a syntax error in the source\n     *  string or a duplicated key.\n     */\n    public JSONObject(String source) throws JSONException {\n        this(new JSONTokener(source));\n    }\n\n\n    /**\n     * Construct a JSONObject from a ResourceBundle.\n     * @param baseName The ResourceBundle base name.\n     * @param locale The Locale to load the ResourceBundle for.\n     * @throws JSONException If any JSONExceptions are detected.\n     */\n    public JSONObject(String baseName, Locale locale) throws JSONException {\n        this();\n        ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, \n                Thread.currentThread().getContextClassLoader());\n\n// Iterate through the keys in the bundle.\n        \n        Enumeration keys = bundle.getKeys();\n        while (keys.hasMoreElements()) {\n            Object key = keys.nextElement();\n            if (key instanceof String) {\n    \n// Go through the path, ensuring that there is a nested JSONObject for each \n// segment except the last. Add the value using the last segment's name into\n// the deepest nested JSONObject.\n                \n                String[] path = ((String)key).split(\"\\\\.\");\n                int last = path.length - 1;\n                JSONObject target = this;\n                for (int i = 0; i < last; i += 1) {\n                    String segment = path[i];\n                    JSONObject nextTarget = target.optJSONObject(segment);\n                    if (nextTarget == null) {\n                        nextTarget = new JSONObject();\n                        target.put(segment.toLowerCase(), nextTarget);\n                    }\n                    target = nextTarget;\n                }\n                target.put(path[last].toLowerCase(), bundle.getString((String)key));\n            }\n        }\n    }\n\n    \n    /**\n     * Accumulate values under a key. It is similar to the put method except\n     * that if there is already an object stored under the key then a\n     * JSONArray is stored under the key to hold all of the accumulated values.\n     * If there is already a JSONArray, then the new value is appended to it.\n     * In contrast, the put method replaces the previous value.\n     * \n     * If only one value is accumulated that is not a JSONArray, then the\n     * result will be the same as using put. But if multiple values are \n     * accumulated, then the result will be like append.\n     * @param key   A key string.\n     * @param value An object to be accumulated under the key.\n     * @return this.\n     * @throws JSONException If the value is an invalid number\n     *  or if the key is null.\n     */\n    public JSONObject accumulate(\n        String key, \n        Object value\n    ) throws JSONException {\n        testValidity(value);\n        Object object = opt(key);\n        if (object == null) {\n            put(key.toLowerCase(), value instanceof JSONArray ?\n                    new JSONArray().put(value) : value);\n        } else if (object instanceof JSONArray) {\n            ((JSONArray)object).put(value);\n        } else {\n            put(key.toLowerCase(), new JSONArray().put(object).put(value));\n        }\n        return this;\n    }\n\n\n    /**\n     * Append values to the array under a key. If the key does not exist in the\n     * JSONObject, then the key is put in the JSONObject with its value being a\n     * JSONArray containing the value parameter. If the key was already\n     * associated with a JSONArray, then the value parameter is appended to it.\n     * @param key   A key string.\n     * @param value An object to be accumulated under the key.\n     * @return this.\n     * @throws JSONException If the key is null or if the current value\n     *  associated with the key is not a JSONArray.\n     */\n    public JSONObject append(String key, Object value) throws JSONException {\n        testValidity(value);\n        Object object = opt(key);\n        if (object == null) {\n            put(key.toLowerCase(), new JSONArray().put(value));\n        } else if (object instanceof JSONArray) {\n            put(key.toLowerCase(), ((JSONArray)object).put(value));\n        } else {\n            throw new JSONException(\"JSONObject[\" + key +\n                    \"] is not a JSONArray.\");\n        }\n        return this;\n    }\n\n\n    /**\n     * Produce a string from a double. The string \"null\" will be returned if\n     * the number is not finite.\n     * @param  d A double.\n     * @return A String.\n     */\n    public static String doubleToString(double d) {\n        if (Double.isInfinite(d) || Double.isNaN(d)) {\n            return \"null\";\n        }\n\n// Shave off trailing zeros and decimal point, if possible.\n\n        String string = Double.toString(d);\n        if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && \n        \t\tstring.indexOf('E') < 0) {\n            while (string.endsWith(\"0\")) {\n                string = string.substring(0, string.length() - 1);\n            }\n            if (string.endsWith(\".\")) {\n                string = string.substring(0, string.length() - 1);\n            }\n        }\n        return string;\n    }\n\n\n    /**\n     * Get the value object associated with a key.\n     *\n     * @param key   A key string.\n     * @return      The object associated with the key.\n     * @throws      JSONException if the key is not found.\n     */\n    public Object get(String key) throws JSONException {\n        if (key == null) {\n            throw new JSONException(\"Null key.\");\n        }\n        Object object = opt(key);\n        if (object == null) {\n            throw new JSONException(\"JSONObject[\" + quote(key) +\n                    \"] not found.\");\n        }\n        return object;\n    }\n\n\n    /**\n     * Get the boolean value associated with a key.\n     *\n     * @param key   A key string.\n     * @return      The truth.\n     * @throws      JSONException\n     *  if the value is not a Boolean or the String \"true\" or \"false\".\n     */\n    public boolean getBoolean(String key) throws JSONException {\n        Object object = get(key);\n        if (object.equals(Boolean.FALSE) ||\n                (object instanceof String &&\n                ((String)object).equalsIgnoreCase(\"false\"))) {\n            return false;\n        } else if (object.equals(Boolean.TRUE) ||\n                (object instanceof String &&\n                ((String)object).equalsIgnoreCase(\"true\"))) {\n            return true;\n        }\n        throw new JSONException(\"JSONObject[\" + quote(key) +\n                \"] is not a Boolean.\");\n    }\n\n\n    /**\n     * Get the double value associated with a key.\n     * @param key   A key string.\n     * @return      The numeric value.\n     * @throws JSONException if the key is not found or\n     *  if the value is not a Number object and cannot be converted to a number.\n     */\n    public double getDouble(String key) throws JSONException {\n        Object object = get(key);\n        try {\n            return object instanceof Number ?\n                ((Number)object).doubleValue() :\n                Double.parseDouble((String)object);\n        } catch (Exception e) {\n            throw new JSONException(\"JSONObject[\" + quote(key) +\n                \"] is not a number.\");\n        }\n    }\n\n\n    /**\n     * Get the int value associated with a key. \n     *\n     * @param key   A key string.\n     * @return      The integer value.\n     * @throws   JSONException if the key is not found or if the value cannot\n     *  be converted to an integer.\n     */\n    public int getInt(String key) throws JSONException {\n        Object object = get(key);\n        try {\n            return object instanceof Number ?\n                ((Number)object).intValue() :\n                Integer.parseInt((String)object);\n        } catch (Exception e) {\n            throw new JSONException(\"JSONObject[\" + quote(key) +\n                \"] is not an int.\");\n        }\n    }\n\n\n    /**\n     * Get the JSONArray value associated with a key.\n     *\n     * @param key   A key string.\n     * @return      A JSONArray which is the value.\n     * @throws      JSONException if the key is not found or\n     *  if the value is not a JSONArray.\n     */\n    public JSONArray getJSONArray(String key) throws JSONException {\n        Object object = get(key);\n        if (object instanceof JSONArray) {\n            return (JSONArray)object;\n        }\n        throw new JSONException(\"JSONObject[\" + quote(key) +\n                \"] is not a JSONArray.\");\n    }\n\n\n    /**\n     * Get the JSONObject value associated with a key.\n     *\n     * @param key   A key string.\n     * @return      A JSONObject which is the value.\n     * @throws      JSONException if the key is not found or\n     *  if the value is not a JSONObject.\n     */\n    public JSONObject getJSONObject(String key) throws JSONException {\n        Object object = get(key);\n        if (object instanceof JSONObject) {\n            return (JSONObject)object;\n        }\n        throw new JSONException(\"JSONObject[\" + quote(key) +\n                \"] is not a JSONObject.\");\n    }\n\n\n    /**\n     * Get the long value associated with a key. \n     *\n     * @param key   A key string.\n     * @return      The long value.\n     * @throws   JSONException if the key is not found or if the value cannot\n     *  be converted to a long.\n     */\n    public long getLong(String key) throws JSONException {\n        Object object = get(key);\n        try {\n            return object instanceof Number ?\n                ((Number)object).longValue() :\n                Long.parseLong((String)object);\n        } catch (Exception e) {\n            throw new JSONException(\"JSONObject[\" + quote(key) +\n                \"] is not a long.\");\n        }\n    }\n\n\n    /**\n     * Get an array of field names from a JSONObject.\n     *\n     * @return An array of field names, or null if there are no names.\n     */\n    public static String[] getNames(JSONObject jo) {\n        int length = jo.length();\n        if (length == 0) {\n            return null;\n        }\n        Iterator iterator = jo.keys();\n        String[] names = new String[length];\n        int i = 0;\n        while (iterator.hasNext()) {\n            names[i] = (String)iterator.next();\n            i += 1;\n        }\n        return names;\n    }\n\n\n    /**\n     * Get an array of field names from an Object.\n     *\n     * @return An array of field names, or null if there are no names.\n     */\n    public static String[] getNames(Object object) {\n        if (object == null) {\n            return null;\n        }\n        Class klass = object.getClass();\n        Field[] fields = klass.getFields();\n        int length = fields.length;\n        if (length == 0) {\n            return null;\n        }\n        String[] names = new String[length];\n        for (int i = 0; i < length; i += 1) {\n            names[i] = fields[i].getName();\n        }\n        return names;\n    }\n\n\n    /**\n     * Get the string associated with a key.\n     *\n     * @param key   A key string.\n     * @return      A string which is the value.\n     * @throws   JSONException if there is no string value for the key.\n     */\n    public String getString(String key) throws JSONException {\n        Object object = get(key);\n        if (object instanceof String) {\n            return (String)object;\n        }\n        throw new JSONException(\"JSONObject[\" + quote(key) +\n            \"] not a string.\");\n    }\n\n\n    /**\n     * Determine if the JSONObject contains a specific key.\n     * @param key   A key string.\n     * @return      true if the key exists in the JSONObject.\n     */\n    public boolean has(String key) {\n        return this.map.containsKey(key);\n    }\n    \n    \n    /**\n     * Increment a property of a JSONObject. If there is no such property,\n     * create one with a value of 1. If there is such a property, and if\n     * it is an Integer, Long, Double, or Float, then add one to it.\n     * @param key  A key string.\n     * @return this.\n     * @throws JSONException If there is already a property with this name\n     * that is not an Integer, Long, Double, or Float.\n     */\n    public JSONObject increment(String key) throws JSONException {\n        Object value = opt(key);\n        if (value == null) {\n            put(key, 1);\n        } else if (value instanceof Integer) {\n            put(key, ((Integer)value).intValue() + 1);\n        } else if (value instanceof Long) {\n            put(key, ((Long)value).longValue() + 1);                \n        } else if (value instanceof Double) {\n            put(key, ((Double)value).doubleValue() + 1);                \n        } else if (value instanceof Float) {\n            put(key, ((Float)value).floatValue() + 1);                \n        } else {\n            throw new JSONException(\"Unable to increment [\" + quote(key) + \"].\");\n        }\n        return this;\n    }\n\n\n    /**\n     * Determine if the value associated with the key is null or if there is\n     *  no value.\n     * @param key   A key string.\n     * @return      true if there is no value associated with the key or if\n     *  the value is the JSONObject.NULL object.\n     */\n    public boolean isNull(String key) {\n        return JSONObject.NULL.equals(opt(key));\n    }\n\n\n    /**\n     * Get an enumeration of the keys of the JSONObject.\n     *\n     * @return An iterator of the keys.\n     */\n    public Iterator keys() {\n        return this.map.keySet().iterator();\n    }\n\n\n    /**\n     * Get the number of keys stored in the JSONObject.\n     *\n     * @return The number of keys in the JSONObject.\n     */\n    public int length() {\n        return this.map.size();\n    }\n\n\n    /**\n     * Produce a JSONArray containing the names of the elements of this\n     * JSONObject.\n     * @return A JSONArray containing the key strings, or null if the JSONObject\n     * is empty.\n     */\n    public JSONArray names() {\n        JSONArray ja = new JSONArray();\n        Iterator  keys = this.keys();\n        while (keys.hasNext()) {\n            ja.put(keys.next());\n        }\n        return ja.length() == 0 ? null : ja;\n    }\n\n    /**\n     * Produce a string from a Number.\n     * @param  number A Number\n     * @return A String.\n     * @throws JSONException If n is a non-finite number.\n     */\n    public static String numberToString(Number number)\n            throws JSONException {\n        if (number == null) {\n            throw new JSONException(\"Null pointer\");\n        }\n        testValidity(number);\n\n// Shave off trailing zeros and decimal point, if possible.\n\n        String string = number.toString();\n        if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && \n        \t\tstring.indexOf('E') < 0) {\n            while (string.endsWith(\"0\")) {\n                string = string.substring(0, string.length() - 1);\n            }\n            if (string.endsWith(\".\")) {\n                string = string.substring(0, string.length() - 1);\n            }\n        }\n        return string;\n    }\n\n\n    /**\n     * Get an optional value associated with a key.\n     * @param key   A key string.\n     * @return      An object which is the value, or null if there is no value.\n     */\n    public Object opt(String key) {\n        return key == null ? null : this.map.get(key);\n    }\n\n\n    /**\n     * Get an optional boolean associated with a key.\n     * It returns false if there is no such key, or if the value is not\n     * Boolean.TRUE or the String \"true\".\n     *\n     * @param key   A key string.\n     * @return      The truth.\n     */\n    public boolean optBoolean(String key) {\n        return optBoolean(key, false);\n    }\n\n\n    /**\n     * Get an optional boolean associated with a key.\n     * It returns the defaultValue if there is no such key, or if it is not\n     * a Boolean or the String \"true\" or \"false\" (case insensitive).\n     *\n     * @param key              A key string.\n     * @param defaultValue     The default.\n     * @return      The truth.\n     */\n    public boolean optBoolean(String key, boolean defaultValue) {\n        try {\n            return getBoolean(key);\n        } catch (Exception e) {\n            return defaultValue;\n        }\n    }\n\n\n    /**\n     * Get an optional double associated with a key,\n     * or NaN if there is no such key or if its value is not a number.\n     * If the value is a string, an attempt will be made to evaluate it as\n     * a number.\n     *\n     * @param key   A string which is the key.\n     * @return      An object which is the value.\n     */\n    public double optDouble(String key) {\n        return optDouble(key, Double.NaN);\n    }\n\n\n    /**\n     * Get an optional double associated with a key, or the\n     * defaultValue if there is no such key or if its value is not a number.\n     * If the value is a string, an attempt will be made to evaluate it as\n     * a number.\n     *\n     * @param key   A key string.\n     * @param defaultValue     The default.\n     * @return      An object which is the value.\n     */\n    public double optDouble(String key, double defaultValue) {\n        try {\n            return getDouble(key);\n        } catch (Exception e) {\n            return defaultValue;\n        }\n    }\n\n\n    /**\n     * Get an optional int value associated with a key,\n     * or zero if there is no such key or if the value is not a number.\n     * If the value is a string, an attempt will be made to evaluate it as\n     * a number.\n     *\n     * @param key   A key string.\n     * @return      An object which is the value.\n     */\n    public int optInt(String key) {\n        return optInt(key, 0);\n    }\n\n\n    /**\n     * Get an optional int value associated with a key,\n     * or the default if there is no such key or if the value is not a number.\n     * If the value is a string, an attempt will be made to evaluate it as\n     * a number.\n     *\n     * @param key   A key string.\n     * @param defaultValue     The default.\n     * @return      An object which is the value.\n     */\n    public int optInt(String key, int defaultValue) {\n        try {\n            return getInt(key);\n        } catch (Exception e) {\n            return defaultValue;\n        }\n    }\n\n\n    /**\n     * Get an optional JSONArray associated with a key.\n     * It returns null if there is no such key, or if its value is not a\n     * JSONArray.\n     *\n     * @param key   A key string.\n     * @return      A JSONArray which is the value.\n     */\n    public JSONArray optJSONArray(String key) {\n        Object o = opt(key);\n        return o instanceof JSONArray ? (JSONArray)o : null;\n    }\n\n\n    /**\n     * Get an optional JSONObject associated with a key.\n     * It returns null if there is no such key, or if its value is not a\n     * JSONObject.\n     *\n     * @param key   A key string.\n     * @return      A JSONObject which is the value.\n     */\n    public JSONObject optJSONObject(String key) {\n        Object object = opt(key);\n        return object instanceof JSONObject ? (JSONObject)object : null;\n    }\n\n\n    /**\n     * Get an optional long value associated with a key,\n     * or zero if there is no such key or if the value is not a number.\n     * If the value is a string, an attempt will be made to evaluate it as\n     * a number.\n     *\n     * @param key   A key string.\n     * @return      An object which is the value.\n     */\n    public long optLong(String key) {\n        return optLong(key, 0);\n    }\n\n\n    /**\n     * Get an optional long value associated with a key,\n     * or the default if there is no such key or if the value is not a number.\n     * If the value is a string, an attempt will be made to evaluate it as\n     * a number.\n     *\n     * @param key          A key string.\n     * @param defaultValue The default.\n     * @return             An object which is the value.\n     */\n    public long optLong(String key, long defaultValue) {\n        try {\n            return getLong(key);\n        } catch (Exception e) {\n            return defaultValue;\n        }\n    }\n\n\n    /**\n     * Get an optional string associated with a key.\n     * It returns an empty string if there is no such key. If the value is not\n     * a string and is not null, then it is converted to a string.\n     *\n     * @param key   A key string.\n     * @return      A string which is the value.\n     */\n    public String optString(String key) {\n        return optString(key, \"\");\n    }\n\n\n    /**\n     * Get an optional string associated with a key.\n     * It returns the defaultValue if there is no such key.\n     *\n     * @param key   A key string.\n     * @param defaultValue     The default.\n     * @return      A string which is the value.\n     */\n    public String optString(String key, String defaultValue) {\n        Object object = opt(key);\n        return NULL.equals(object) ? defaultValue : object.toString();        \n    }\n\n\n    private void populateMap(Object bean) {\n        Class klass = bean.getClass();\n\n// If klass is a System class then set includeSuperClass to false. \n\n        boolean includeSuperClass = klass.getClassLoader() != null;\n\n        Method[] methods = (includeSuperClass) ?\n                klass.getMethods() : klass.getDeclaredMethods();\n        for (int i = 0; i < methods.length; i += 1) {\n            try {\n                Method method = methods[i];\n                if (Modifier.isPublic(method.getModifiers())) {\n                    String name = method.getName();\n                    String key = \"\";\n                    if (name.startsWith(\"get\")) {\n                        if (name.equals(\"getClass\") || \n                                name.equals(\"getDeclaringClass\")) {\n                            key = \"\";\n                        } else {\n                            key = name.substring(3);\n                        }\n                    } else if (name.startsWith(\"is\")) {\n                        key = name.substring(2);\n                    }\n                    if (key.length() > 0 &&\n                            Character.isUpperCase(key.charAt(0)) &&\n                            method.getParameterTypes().length == 0) {\n                        if (key.length() == 1) {\n                            key = key.toLowerCase();\n                        } else if (!Character.isUpperCase(key.charAt(1))) {\n                            key = key.substring(0, 1).toLowerCase() +\n                                key.substring(1);\n                        }\n\n                        Object result = method.invoke(bean, (Object[])null);\n                        if (result != null) {\n                            map.put(key, wrap(result));\n                        }\n                    }\n                }\n            } catch (Exception ignore) {\n            }\n        }\n    }\n\n\n    /**\n     * Put a key/boolean pair in the JSONObject.\n     *\n     * @param key   A key string.\n     * @param value A boolean which is the value.\n     * @return this.\n     * @throws JSONException If the key is null.\n     */\n    public JSONObject put(String key, boolean value) throws JSONException {\n        put(key, value ? Boolean.TRUE : Boolean.FALSE);\n        return this;\n    }\n\n\n    /**\n     * Put a key/value pair in the JSONObject, where the value will be a\n     * JSONArray which is produced from a Collection.\n     * @param key   A key string.\n     * @param value A Collection value.\n     * @return      this.\n     * @throws JSONException\n     */\n    public JSONObject put(String key, Collection value) throws JSONException {\n        put(key, new JSONArray(value));\n        return this;\n    }\n\n\n    /**\n     * Put a key/double pair in the JSONObject.\n     *\n     * @param key   A key string.\n     * @param value A double which is the value.\n     * @return this.\n     * @throws JSONException If the key is null or if the number is invalid.\n     */\n    public JSONObject put(String key, double value) throws JSONException {\n        put(key, new Double(value));\n        return this;\n    }\n\n\n    /**\n     * Put a key/int pair in the JSONObject.\n     *\n     * @param key   A key string.\n     * @param value An int which is the value.\n     * @return this.\n     * @throws JSONException If the key is null.\n     */\n    public JSONObject put(String key, int value) throws JSONException {\n        put(key, new Integer(value));\n        return this;\n    }\n\n\n    /**\n     * Put a key/long pair in the JSONObject.\n     *\n     * @param key   A key string.\n     * @param value A long which is the value.\n     * @return this.\n     * @throws JSONException If the key is null.\n     */\n    public JSONObject put(String key, long value) throws JSONException {\n        put(key, new Long(value));\n        return this;\n    }\n\n\n    /**\n     * Put a key/value pair in the JSONObject, where the value will be a\n     * JSONObject which is produced from a Map.\n     * @param key   A key string.\n     * @param value A Map value.\n     * @return      this.\n     * @throws JSONException\n     */\n    public JSONObject put(String key, Map value) throws JSONException {\n        put(key, new JSONObject(value));\n        return this;\n    }\n\n\n    /**\n     * Put a key/value pair in the JSONObject. If the value is null,\n     * then the key will be removed from the JSONObject if it is present.\n     * @param key   A key string.\n     * @param value An object which is the value. It should be of one of these\n     *  types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,\n     *  or the JSONObject.NULL object.\n     * @return this.\n     * @throws JSONException If the value is non-finite number\n     *  or if the key is null.\n     */\n    public JSONObject put(String key, Object value) throws JSONException {\n        if (key == null) {\n            throw new JSONException(\"Null key.\");\n        }\n        if (value != null) {\n            testValidity(value);\n            this.map.put(key, value);\n        } else {\n            remove(key);\n        }\n        return this;\n    }\n\n\n    /**\n     * Put a key/value pair in the JSONObject, but only if the key and the\n     * value are both non-null, and only if there is not already a member\n     * with that name.\n     * @param key\n     * @param value\n     * @return his.\n     * @throws JSONException if the key is a duplicate\n     */\n    public final JSONObject putOnce(String key, Object value) throws JSONException {\n        if (key != null && value != null) {\n            if (opt(key) != null) {\n                throw new JSONException(\"Duplicate key \\\"\" + key + \"\\\"\");\n            }\n            put(key, value);\n        }\n        return this;\n    }\n\n\n    /**\n     * Put a key/value pair in the JSONObject, but only if the\n     * key and the value are both non-null.\n     * @param key   A key string.\n     * @param value An object which is the value. It should be of one of these\n     *  types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,\n     *  or the JSONObject.NULL object.\n     * @return this.\n     * @throws JSONException If the value is a non-finite number.\n     */\n    public JSONObject putOpt(String key, Object value) throws JSONException {\n        if (key != null && value != null) {\n            put(key, value);\n        }\n        return this;\n    }\n\n\n    /**\n     * Produce a string in double quotes with backslash sequences in all the\n     * right places. A backslash will be inserted within </, producing <\\/,\n     * allowing JSON text to be delivered in HTML. In JSON text, a string \n     * cannot contain a control character or an unescaped quote or backslash.\n     * @param string A String\n     * @return  A String correctly formatted for insertion in a JSON text.\n     */\n    public static String quote(String string) {\n        if (string == null || string.length() == 0) {\n            return \"\\\"\\\"\";\n        }\n\n        char         b;\n        char         c = 0;\n        String       hhhh;\n        int          i;\n        int          len = string.length();\n        StringBuilder sb = new StringBuilder(len + 4);\n\n        sb.append('\"');\n        for (i = 0; i < len; i += 1) {\n            b = c;\n            c = string.charAt(i);\n            switch (c) {\n            case '\\\\':\n            case '\"':\n                sb.append('\\\\');\n                sb.append(c);\n                break;\n            case '/':\n                if (b == '<') {\n                    sb.append('\\\\');\n                }\n                sb.append(c);\n                break;\n            case '\\b':\n                sb.append(\"\\\\b\");\n                break;\n            case '\\t':\n                sb.append(\"\\\\t\");\n                break;\n            case '\\n':\n                sb.append(\"\\\\n\");\n                break;\n            case '\\f':\n                sb.append(\"\\\\f\");\n                break;\n            case '\\r':\n                sb.append(\"\\\\r\");\n                break;\n            default:\n                if (c < ' ' || (c >= '\\u0080' && c < '\\u00a0') ||\n                               (c >= '\\u2000' && c < '\\u2100')) {\n                    hhhh = \"000\" + Integer.toHexString(c);\n                    sb.append(\"\\\\u\" + hhhh.substring(hhhh.length() - 4));\n                } else {\n                    sb.append(c);\n                }\n            }\n        }\n        sb.append('\"');\n        return sb.toString();\n    }\n\n    /**\n     * Remove a name and its value, if present.\n     * @param key The name to be removed.\n     * @return The value that was associated with the name,\n     * or null if there was no value.\n     */\n    public Object remove(String key) {\n        return this.map.remove(key);\n    }\n\n    /**\n     * Try to convert a string into a number, boolean, or null. If the string\n     * can't be converted, return the string.\n     * @param string A String.\n     * @return A simple JSON value.\n     */\n    public static Object stringToValue(String string) {\n        if (string.equals(\"\")) {\n            return string;\n        }\n        if (string.equalsIgnoreCase(\"true\")) {\n            return Boolean.TRUE;\n        }\n        if (string.equalsIgnoreCase(\"false\")) {\n            return Boolean.FALSE;\n        }\n        if (string.equalsIgnoreCase(\"null\")) {\n            return JSONObject.NULL;\n        }\n\n        /*\n         * If it might be a number, try converting it. \n         * We support the non-standard 0x- convention. \n         * If a number cannot be produced, then the value will just\n         * be a string. Note that the 0x-, plus, and implied string\n         * conventions are non-standard. A JSON parser may accept\n         * non-JSON forms as long as it accepts all correct JSON forms.\n         */\n\n        char b = string.charAt(0);\n        if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {\n            if (b == '0' && string.length() > 2 &&\n                        (string.charAt(1) == 'x' || string.charAt(1) == 'X')) {\n                try {\n                    return new Integer(Integer.parseInt(string.substring(2), 16));\n                } catch (Exception ignore) {\n                }\n            }\n            try {\n                if (string.indexOf('.') > -1 || \n                        string.indexOf('e') > -1 || string.indexOf('E') > -1) {\n                    return Double.valueOf(string);\n                } else {\n                    Long myLong = new Long(string);\n                    if (myLong.longValue() == myLong.intValue()) {\n                        return new Integer(myLong.intValue());\n                    } else {\n                        return myLong;\n                    }\n                }\n            }  catch (Exception ignore) {\n            }\n        }\n        return string;\n    }\n\n\n    /**\n     * Throw an exception if the object is a NaN or infinite number.\n     * @param o The object to test.\n     * @throws JSONException If o is a non-finite number.\n     */\n    public static void testValidity(Object o) throws JSONException {\n        if (o != null) {\n            if (o instanceof Double) {\n                if (((Double)o).isInfinite() || ((Double)o).isNaN()) {\n                    throw new JSONException(\n                        \"JSON does not allow non-finite numbers.\");\n                }\n            } else if (o instanceof Float) {\n                if (((Float)o).isInfinite() || ((Float)o).isNaN()) {\n                    throw new JSONException(\n                        \"JSON does not allow non-finite numbers.\");\n                }\n            }\n        }\n    }\n\n\n    /**\n     * Produce a JSONArray containing the values of the members of this\n     * JSONObject.\n     * @param names A JSONArray containing a list of key strings. This\n     * determines the sequence of the values in the result.\n     * @return A JSONArray of values.\n     * @throws JSONException If any of the values are non-finite numbers.\n     */\n    public JSONArray toJSONArray(JSONArray names) throws JSONException {\n        if (names == null || names.length() == 0) {\n            return null;\n        }\n        JSONArray ja = new JSONArray();\n        for (int i = 0; i < names.length(); i += 1) {\n            ja.put(this.opt(names.getString(i)));\n        }\n        return ja;\n    }\n\n    /**\n     * Make a JSON text of this JSONObject. For compactness, no whitespace\n     * is added. If this would not result in a syntactically correct JSON text,\n     * then null will be returned instead.\n     * <p>\n     * Warning: This method assumes that the data structure is acyclical.\n     *\n     * @return a printable, displayable, portable, transmittable\n     *  representation of the object, beginning\n     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending\n     *  with <code>}</code>&nbsp;<small>(right brace)</small>.\n     */\n    @Override\n    public String toString() {\n        try {\n            Iterator     keys = this.keys();\n            StringBuilder sb = new StringBuilder(\"{\");\n\n            while (keys.hasNext()) {\n                if (sb.length() > 1) {\n                    sb.append(',');\n                }\n                Object o = keys.next();\n                sb.append(quote(o.toString()));\n                sb.append(':');\n                sb.append(valueToString(this.map.get(o)));\n            }\n            sb.append('}');\n            return sb.toString();\n        } catch (Exception e) {\n            return null;\n        }\n    }\n\n    /**\n     * Make a prettyprinted JSON text of this JSONObject.\n     * <p>\n     * Warning: This method assumes that the data structure is acyclical.\n     * @param indentFactor The number of spaces to add to each level of\n     *  indentation.\n     * @return a printable, displayable, portable, transmittable\n     *  representation of the object, beginning\n     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending\n     *  with <code>}</code>&nbsp;<small>(right brace)</small>.\n     * @throws JSONException If the object contains an invalid number.\n     */\n    public String toString(int indentFactor) throws JSONException {\n        return toString(indentFactor, 0);\n    }\n\n\n    /**\n     * Make a prettyprinted JSON text of this JSONObject.\n     * <p>\n     * Warning: This method assumes that the data structure is acyclical.\n     * @param indentFactor The number of spaces to add to each level of\n     *  indentation.\n     * @param indent The indentation of the top level.\n     * @return a printable, displayable, transmittable\n     *  representation of the object, beginning\n     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending\n     *  with <code>}</code>&nbsp;<small>(right brace)</small>.\n     * @throws JSONException If the object contains an invalid number.\n     */\n    String toString(int indentFactor, int indent) throws JSONException {\n        int i;\n        int length = this.length();\n        if (length == 0) {\n            return \"{}\";\n        }\n        Iterator     keys = this.keys();\n        int          newindent = indent + indentFactor;\n        Object       object;\n        StringBuilder sb = new StringBuilder(\"{\");\n        if (length == 1) {\n            object = keys.next();\n            sb.append(quote(object.toString()));\n            sb.append(\": \");\n            sb.append(valueToString(this.map.get(object), indentFactor,\n                    indent));\n        } else {\n            while (keys.hasNext()) {\n                object = keys.next();\n                if (sb.length() > 1) {\n                    sb.append(\",\\n\");\n                } else {\n                    sb.append('\\n');\n                }\n                for (i = 0; i < newindent; i += 1) {\n                    sb.append(' ');\n                }\n                sb.append(quote(object.toString()));\n                sb.append(\": \");\n                sb.append(valueToString(this.map.get(object), indentFactor,\n                        newindent));\n            }\n            if (sb.length() > 1) {\n                sb.append('\\n');\n                for (i = 0; i < indent; i += 1) {\n                    sb.append(' ');\n                }\n            }\n        }\n        sb.append('}');\n        return sb.toString();\n    }\n\n\n    /**\n     * Make a JSON text of an Object value. If the object has an\n     * value.toJSONString() method, then that method will be used to produce\n     * the JSON text. The method is required to produce a strictly\n     * conforming text. If the object does not contain a toJSONString\n     * method (which is the most common case), then a text will be\n     * produced by other means. If the value is an array or Collection,\n     * then a JSONArray will be made from it and its toJSONString method\n     * will be called. If the value is a MAP, then a JSONObject will be made\n     * from it and its toJSONString method will be called. Otherwise, the\n     * value's toString method will be called, and the result will be quoted.\n     *\n     * <p>\n     * Warning: This method assumes that the data structure is acyclical.\n     * @param value The value to be serialized.\n     * @return a printable, displayable, transmittable\n     *  representation of the object, beginning\n     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending\n     *  with <code>}</code>&nbsp;<small>(right brace)</small>.\n     * @throws JSONException If the value is or contains an invalid number.\n     */\n    public static String valueToString(Object value) throws JSONException {\n        if (value == null || value.equals(null)) {\n            return \"null\";\n        }\n        if (value instanceof JSONString) {\n            Object object;\n            try {\n                object = ((JSONString)value).toJSONString();\n            } catch (Exception e) {\n                throw new JSONException(e);\n            }\n            if (object instanceof String) {\n                return (String)object;\n            }\n            throw new JSONException(\"Bad value from toJSONString: \" + object);\n        }\n        if (value instanceof Number) {\n            return numberToString((Number) value);\n        }\n        if (value instanceof Boolean || value instanceof JSONObject ||\n                value instanceof JSONArray) {\n            return value.toString();\n        }\n        if (value instanceof Map) {\n            return new JSONObject((Map)value).toString();\n        }\n        if (value instanceof Collection) {\n            return new JSONArray((Collection)value).toString();\n        }\n        if (value.getClass().isArray()) {\n            return new JSONArray(value).toString();\n        }\n        return quote(value.toString());\n    }\n\n\n    /**\n     * Make a prettyprinted JSON text of an object value.\n     * <p>\n     * Warning: This method assumes that the data structure is acyclical.\n     * @param value The value to be serialized.\n     * @param indentFactor The number of spaces to add to each level of\n     *  indentation.\n     * @param indent The indentation of the top level.\n     * @return a printable, displayable, transmittable\n     *  representation of the object, beginning\n     *  with <code>{</code>&nbsp;<small>(left brace)</small> and ending\n     *  with <code>}</code>&nbsp;<small>(right brace)</small>.\n     * @throws JSONException If the object contains an invalid number.\n     */\n     static String valueToString(\n         Object value, \n         int    indentFactor, \n         int    indent\n     ) throws JSONException {\n        if (value == null ) {\n            return \"null\";\n        }\n        try {\n            if (value instanceof JSONString) {\n                Object o = ((JSONString)value).toJSONString();\n                if (o instanceof String) {\n                    return (String)o;\n                }\n            }\n        } catch (Exception ignore) {\n        }\n        if (value instanceof Number) {\n            return numberToString((Number) value);\n        }\n        if (value instanceof Boolean) {\n            return value.toString();\n        }\n        if (value instanceof JSONObject) {\n            return ((JSONObject)value).toString(indentFactor, indent);\n        }\n        if (value instanceof JSONArray) {\n            return ((JSONArray)value).toString(indentFactor, indent);\n        }\n        if (value instanceof Map) {\n            return new JSONObject((Map)value).toString(indentFactor, indent);\n        }\n        if (value instanceof Collection) {\n            return new JSONArray((Collection)value).toString(indentFactor, indent);\n        }\n        if (value.getClass().isArray()) {\n            return new JSONArray(value).toString(indentFactor, indent);\n        }\n        return quote(value.toString());\n    }\n\n\n     /**\n      * Wrap an object, if necessary. If the object is null, return the NULL \n      * object. If it is an array or collection, wrap it in a JSONArray. If \n      * it is a map, wrap it in a JSONObject. If it is a standard property \n      * (Double, String, et al) then it is already wrapped. Otherwise, if it \n      * comes from one of the java packages, turn it into a string. And if \n      * it doesn't, try to wrap it in a JSONObject. If the wrapping fails,\n      * then null is returned.\n      *\n      * @param object The object to wrap\n      * @return The wrapped value\n      */\n     public static Object wrap(Object object) {\n         try {\n             if (object == null) {\n                 return NULL;\n             }\n             if (object instanceof JSONObject || object instanceof JSONArray  || \n                     NULL.equals(object)      || object instanceof JSONString || \n                     object instanceof Byte   || object instanceof Character  ||\n                     object instanceof Short  || object instanceof Integer    ||\n                     object instanceof Long   || object instanceof Boolean    || \n                     object instanceof Float  || object instanceof Double     ||\n                     object instanceof String) {\n                 return object;\n             }\n             \n             if (object instanceof Collection) {\n                 return new JSONArray((Collection)object);\n             }\n             if (object.getClass().isArray()) {\n                 return new JSONArray(object);\n             }\n             if (object instanceof Map) {\n                 return new JSONObject((Map)object);\n             }\n             Package objectPackage = object.getClass().getPackage();\n             String objectPackageName = objectPackage != null ? \n                 objectPackage.getName() : \"\";\n             if (\n                 objectPackageName.startsWith(\"java.\") ||\n                 objectPackageName.startsWith(\"javax.\") ||\n                 object.getClass().getClassLoader() == null\n             ) {\n                 return object.toString();\n             }\n             return new JSONObject(object);\n         } catch(Exception exception) {\n             return null;\n         }\n     }\n\n     \n     /**\n      * Write the contents of the JSONObject as JSON text to a writer.\n      * For compactness, no whitespace is added.\n      * <p>\n      * Warning: This method assumes that the data structure is acyclical.\n      *\n      * @return The writer.\n      * @throws JSONException\n      */\n     public Writer write(Writer writer) throws JSONException {\n        try {\n            boolean  commanate = false;\n            Iterator keys = this.keys();\n            writer.write('{');\n\n            while (keys.hasNext()) {\n                if (commanate) {\n                    writer.write(',');\n                }\n                Object key = keys.next();\n                writer.write(quote(key.toString()));\n                writer.write(':');\n                Object value = this.map.get(key);\n                if (value instanceof JSONObject) {\n                    ((JSONObject)value).write(writer);\n                } else if (value instanceof JSONArray) {\n                    ((JSONArray)value).write(writer);\n                } else {\n                    writer.write(valueToString(value));\n                }\n                commanate = true;\n            }\n            writer.write('}');\n            return writer;\n        } catch (IOException exception) {\n            throw new JSONException(exception);\n        }\n     }\n}"
  },
  {
    "path": "src/main/java/org/json/JSONString.java",
    "content": "package org.json;\r\n/**\r\n * The <code>JSONString</code> interface allows a <code>toJSONString()</code> \r\n * method so that a class can change the behavior of \r\n * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>,\r\n * and <code>JSONWriter.value(</code>Object<code>)</code>. The \r\n * <code>toJSONString</code> method will be used instead of the default behavior \r\n * of using the Object's <code>toString()</code> method and quoting the result.\r\n */\r\npublic interface JSONString {\r\n\t/**\r\n\t * The <code>toJSONString</code> method allows a class to produce its own JSON \r\n\t * serialization. \r\n\t * \r\n\t * @return A strictly syntactically correct JSON text.\r\n\t */\r\n\tpublic String toJSONString();\r\n}\r\n"
  },
  {
    "path": "src/main/java/org/json/JSONStringer.java",
    "content": "package org.json;\r\n\r\n/*\r\nCopyright (c) 2006 JSON.org\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nThe Software shall be used for Good, not Evil.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n*/\r\n\r\nimport java.io.StringWriter;\r\n\r\n/**\r\n * JSONStringer provides a quick and convenient way of producing JSON text.\r\n * The texts produced strictly conform to JSON syntax rules. No whitespace is\r\n * added, so the results are ready for transmission or storage. Each instance of\r\n * JSONStringer can produce one JSON text.\r\n * <p>\r\n * A JSONStringer instance provides a <code>value</code> method for appending\r\n * values to the\r\n * text, and a <code>key</code>\r\n * method for adding keys before values in objects. There are <code>array</code>\r\n * and <code>endArray</code> methods that make and bound array values, and\r\n * <code>object</code> and <code>endObject</code> methods which make and bound\r\n * object values. All of these methods return the JSONWriter instance,\r\n * permitting cascade style. For example, <pre>\r\n * myString = new JSONStringer()\r\n *     .object()\r\n *         .key(\"JSON\")\r\n *         .value(\"Hello, World!\")\r\n *     .endObject()\r\n *     .toString();</pre> which produces the string <pre>\r\n * {\"JSON\":\"Hello, World!\"}</pre>\r\n * <p>\r\n * The first method called must be <code>array</code> or <code>object</code>.\r\n * There are no methods for adding commas or colons. JSONStringer adds them for\r\n * you. Objects and arrays can be nested up to 20 levels deep.\r\n * <p>\r\n * This can sometimes be easier than using a JSONObject to build a string.\r\n * @author JSON.org\r\n * @version 2008-09-18\r\n */\r\npublic class JSONStringer extends JSONWriter {\r\n    /**\r\n     * Make a fresh JSONStringer. It can be used to build one JSON text.\r\n     */\r\n    public JSONStringer() {\r\n        super(new StringWriter());\r\n    }\r\n\r\n    /**\r\n     * Return the JSON text. This method is used to obtain the product of the\r\n     * JSONStringer instance. It will return <code>null</code> if there was a\r\n     * problem in the construction of the JSON text (such as the calls to\r\n     * <code>array</code> were not properly balanced with calls to\r\n     * <code>endArray</code>).\r\n     * @return The JSON text.\r\n     */\r\n    public String toString() {\r\n        return this.mode == 'd' ? this.writer.toString() : null;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/main/java/org/json/JSONTokener.java",
    "content": "package org.json;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.io.StringReader;\n\n/*\nCopyright (c) 2002 JSON.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nThe Software shall be used for Good, not Evil.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/**\n * A JSONTokener takes a source string and extracts characters and tokens from\n * it. It is used by the JSONObject and JSONArray constructors to parse\n * JSON source strings.\n * @author JSON.org\n * @version 2010-12-24\n */\npublic class JSONTokener {\n\n    private int \tcharacter;\n\tprivate boolean eof;\n    private int \tindex;\n    private int \tline;\n    private char \tprevious;\n    private Reader \treader;\n    private boolean usePrevious;\n\n\n    /**\n     * Construct a JSONTokener from a Reader.\n     *\n     * @param reader     A reader.\n     */\n    public JSONTokener(Reader reader) {\n        this.reader = reader.markSupported() ? \n        \t\treader : new BufferedReader(reader);\n        this.eof = false;\n        this.usePrevious = false;\n        this.previous = 0;\n        this.index = 0;\n        this.character = 1;\n        this.line = 1;\n    }\n    \n    \n    /**\n     * Construct a JSONTokener from an InputStream.\n     */\n    public JSONTokener(InputStream inputStream) throws JSONException {\n        this(new InputStreamReader(inputStream));    \t\n    }\n\n\n    /**\n     * Construct a JSONTokener from a string.\n     *\n     * @param s     A source string.\n     */\n    public JSONTokener(String s) {\n        this(new StringReader(s));\n    }\n\n\n    /**\n     * Back up one character. This provides a sort of lookahead capability,\n     * so that you can test for a digit or letter before attempting to parse\n     * the next number or identifier.\n     */\n    public void back() throws JSONException {\n        if (usePrevious || index <= 0) {\n            throw new JSONException(\"Stepping back two steps is not supported\");\n        }\n        this.index -= 1;\n        this.character -= 1;\n        this.usePrevious = true;\n        this.eof = false;\n    }\n\n\n    /**\n     * Get the hex value of a character (base16).\n     * @param c A character between '0' and '9' or between 'A' and 'F' or\n     * between 'a' and 'f'.\n     * @return  An int between 0 and 15, or -1 if c was not a hex digit.\n     */\n    public static int dehexchar(char c) {\n        if (c >= '0' && c <= '9') {\n            return c - '0';\n        }\n        if (c >= 'A' && c <= 'F') {\n            return c - ('A' - 10);\n        }\n        if (c >= 'a' && c <= 'f') {\n            return c - ('a' - 10);\n        }\n        return -1;\n    }\n    \n    public boolean end() {\n    \treturn eof && !usePrevious;    \t\n    }\n\n\n    /**\n     * Determine if the source string still contains characters that next()\n     * can consume.\n     * @return true if not yet at the end of the source.\n     */\n    public boolean more() throws JSONException {\n        next();\n        if (end()) {\n            return false;\n        } \n        back();\n        return true;\n    }\n\n\n    /**\n     * Get the next character in the source string.\n     *\n     * @return The next character, or 0 if past the end of the source string.\n     */\n    public char next() throws JSONException {\n        int c;\n        if (this.usePrevious) {\n        \tthis.usePrevious = false;\n            c = this.previous;\n        } else {\n\t        try {\n\t            c = this.reader.read();\n\t        } catch (IOException exception) {\n\t            throw new JSONException(exception);\n\t        }\n\t\n\t        if (c <= 0) { // End of stream\n\t        \tthis.eof = true;\n\t        \tc = 0;\n\t        } \n        }\n    \tthis.index += 1;\n    \tif (this.previous == '\\r') {\n    \t\tthis.line += 1;\n    \t\tthis.character = c == '\\n' ? 0 : 1;\n    \t} else if (c == '\\n') {\n    \t\tthis.line += 1;\n    \t\tthis.character = 0;\n    \t} else {\n    \t\tthis.character += 1;\n    \t}\n    \tthis.previous = (char) c;\n        return this.previous;\n    }\n\n\n    /**\n     * Consume the next character, and check that it matches a specified\n     * character.\n     * @param c The character to match.\n     * @return The character.\n     * @throws JSONException if the character does not match.\n     */\n    public char next(char c) throws JSONException {\n        char n = next();\n        if (n != c) {\n            throw syntaxError(\"Expected '\" + c + \"' and instead saw '\" +\n                    n + \"'\");\n        }\n        return n;\n    }\n\n\n    /**\n     * Get the next n characters.\n     *\n     * @param n     The number of characters to take.\n     * @return      A string of n characters.\n     * @throws JSONException\n     *   Substring bounds error if there are not\n     *   n characters remaining in the source string.\n     */\n     public String next(int n) throws JSONException {\n         if (n == 0) {\n             return \"\";\n         }\n\n         char[] chars = new char[n];\n         int pos = 0;\n\n         while (pos < n) {\n             chars[pos] = next();\n             if (end()) {\n                 throw syntaxError(\"Substring bounds error\");                 \n             }\n             pos += 1;\n         }\n         return new String(chars);\n     }\n\n\n    /**\n     * Get the next char in the string, skipping whitespace.\n     * @throws JSONException\n     * @return  A character, or 0 if there are no more characters.\n     */\n    public char nextClean() throws JSONException {\n        for (;;) {\n            char c = next();\n            if (c == 0 || c > ' ') {\n                return c;\n            }\n        }\n    }\n\n\n    /**\n     * Return the characters up to the next close quote character.\n     * Backslash processing is done. The formal JSON format does not\n     * allow strings in single quotes, but an implementation is allowed to\n     * accept them.\n     * @param quote The quoting character, either\n     *      <code>\"</code>&nbsp;<small>(double quote)</small> or\n     *      <code>'</code>&nbsp;<small>(single quote)</small>.\n     * @return      A String.\n     * @throws JSONException Unterminated string.\n     */\n    public String nextString(char quote) throws JSONException {\n        char c;\n        StringBuffer sb = new StringBuffer();\n        for (;;) {\n            c = next();\n            switch (c) {\n            case 0:\n            case '\\n':\n            case '\\r':\n                throw syntaxError(\"Unterminated string\");\n            case '\\\\':\n                c = next();\n                switch (c) {\n                case 'b':\n                    sb.append('\\b');\n                    break;\n                case 't':\n                    sb.append('\\t');\n                    break;\n                case 'n':\n                    sb.append('\\n');\n                    break;\n                case 'f':\n                    sb.append('\\f');\n                    break;\n                case 'r':\n                    sb.append('\\r');\n                    break;\n                case 'u':\n                    sb.append((char)Integer.parseInt(next(4), 16));\n                    break;\n                case '\"':\n                case '\\'':\n                case '\\\\':\n                case '/':\n                \tsb.append(c);\n                \tbreak;\n                default:\n                    throw syntaxError(\"Illegal escape.\");\n                }\n                break;\n            default:\n                if (c == quote) {\n                    return sb.toString();\n                }\n                sb.append(c);\n            }\n        }\n    }\n\n\n    /**\n     * Get the text up but not including the specified character or the\n     * end of line, whichever comes first.\n     * @param  delimiter A delimiter character.\n     * @return   A string.\n     */\n    public String nextTo(char delimiter) throws JSONException {\n        StringBuffer sb = new StringBuffer();\n        for (;;) {\n            char c = next();\n            if (c == delimiter || c == 0 || c == '\\n' || c == '\\r') {\n                if (c != 0) {\n                    back();\n                }\n                return sb.toString().trim();\n            }\n            sb.append(c);\n        }\n    }\n\n\n    /**\n     * Get the text up but not including one of the specified delimiter\n     * characters or the end of line, whichever comes first.\n     * @param delimiters A set of delimiter characters.\n     * @return A string, trimmed.\n     */\n    public String nextTo(String delimiters) throws JSONException {\n        char c;\n        StringBuffer sb = new StringBuffer();\n        for (;;) {\n            c = next();\n            if (delimiters.indexOf(c) >= 0 || c == 0 ||\n                    c == '\\n' || c == '\\r') {\n                if (c != 0) {\n                    back();\n                }\n                return sb.toString().trim();\n            }\n            sb.append(c);\n        }\n    }\n\n\n    /**\n     * Get the next value. The value can be a Boolean, Double, Integer,\n     * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.\n     * @throws JSONException If syntax error.\n     *\n     * @return An object.\n     */\n    public Object nextValue() throws JSONException {\n        char c = nextClean();\n        String string;\n\n        switch (c) {\n            case '\"':\n            case '\\'':\n                return nextString(c);\n            case '{':\n                back();\n                return new JSONObject(this);\n            case '[':\n                back();\n                return new JSONArray(this);\n        }\n\n        /*\n         * Handle unquoted text. This could be the values true, false, or\n         * null, or it can be a number. An implementation (such as this one)\n         * is allowed to also accept non-standard forms.\n         *\n         * Accumulate characters until we reach the end of the text or a\n         * formatting character.\n         */\n\n        StringBuffer sb = new StringBuffer();\n        while (c >= ' ' && \",:]}/\\\\\\\"[{;=#\".indexOf(c) < 0) {\n            sb.append(c);\n            c = next();\n        }\n        back();\n\n        string = sb.toString().trim();\n        if (string.equals(\"\")) {\n            throw syntaxError(\"Missing value\");\n        }\n        return JSONObject.stringToValue(string);\n    }\n\n\n    /**\n     * Skip characters until the next character is the requested character.\n     * If the requested character is not found, no characters are skipped.\n     * @param to A character to skip to.\n     * @return The requested character, or zero if the requested character\n     * is not found.\n     */\n    public char skipTo(char to) throws JSONException {\n        char c;\n        try {\n            int startIndex = this.index;\n            int startCharacter = this.character;\n            int startLine = this.line;\n            reader.mark(Integer.MAX_VALUE);\n            do {\n                c = next();\n                if (c == 0) {\n                    reader.reset();\n                    this.index = startIndex;\n                    this.character = startCharacter;\n                    this.line = startLine;\n                    return c;\n                }\n            } while (c != to);\n        } catch (IOException exc) {\n            throw new JSONException(exc);\n        }\n\n        back();\n        return c;\n    }\n    \n\n    /**\n     * Make a JSONException to signal a syntax error.\n     *\n     * @param message The error message.\n     * @return  A JSONException object, suitable for throwing\n     */\n    public JSONException syntaxError(String message) {\n        return new JSONException(message + toString());\n    }\n\n\n    /**\n     * Make a printable string of this JSONTokener.\n     *\n     * @return \" at {index} [character {character} line {line}]\"\n     */\n    public String toString() {\n        return \" at \" + index + \" [character \" + this.character + \" line \" + \n        \tthis.line + \"]\";\n    }\n}"
  },
  {
    "path": "src/main/java/org/json/JSONWriter.java",
    "content": "package org.json;\r\n\r\nimport java.io.IOException;\r\nimport java.io.Writer;\r\n\r\n/*\r\nCopyright (c) 2006 JSON.org\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nThe Software shall be used for Good, not Evil.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n*/\r\n\r\n/**\r\n * JSONWriter provides a quick and convenient way of producing JSON text.\r\n * The texts produced strictly conform to JSON syntax rules. No whitespace is\r\n * added, so the results are ready for transmission or storage. Each instance of\r\n * JSONWriter can produce one JSON text.\r\n * <p>\r\n * A JSONWriter instance provides a <code>value</code> method for appending\r\n * values to the\r\n * text, and a <code>key</code>\r\n * method for adding keys before values in objects. There are <code>array</code>\r\n * and <code>endArray</code> methods that make and bound array values, and\r\n * <code>object</code> and <code>endObject</code> methods which make and bound\r\n * object values. All of these methods return the JSONWriter instance,\r\n * permitting a cascade style. For example, <pre>\r\n * new JSONWriter(myWriter)\r\n *     .object()\r\n *         .key(\"JSON\")\r\n *         .value(\"Hello, World!\")\r\n *     .endObject();</pre> which writes <pre>\r\n * {\"JSON\":\"Hello, World!\"}</pre>\r\n * <p>\r\n * The first method called must be <code>array</code> or <code>object</code>.\r\n * There are no methods for adding commas or colons. JSONWriter adds them for\r\n * you. Objects and arrays can be nested up to 20 levels deep.\r\n * <p>\r\n * This can sometimes be easier than using a JSONObject to build a string.\r\n * @author JSON.org\r\n * @version 2010-12-24\r\n */\r\npublic class JSONWriter {\r\n    private static final int maxdepth = 20;\r\n\r\n    /**\r\n     * The comma flag determines if a comma should be output before the next\r\n     * value.\r\n     */\r\n    private boolean comma;\r\n\r\n    /**\r\n     * The current mode. Values:\r\n     * 'a' (array),\r\n     * 'd' (done),\r\n     * 'i' (initial),\r\n     * 'k' (key),\r\n     * 'o' (object).\r\n     */\r\n    protected char mode;\r\n\r\n    /**\r\n     * The object/array stack.\r\n     */\r\n    private JSONObject stack[];\r\n\r\n    /**\r\n     * The stack top index. A value of 0 indicates that the stack is empty.\r\n     */\r\n    private int top;\r\n\r\n    /**\r\n     * The writer that will receive the output.\r\n     */\r\n    protected Writer writer;\r\n\r\n    /**\r\n     * Make a fresh JSONWriter. It can be used to build one JSON text.\r\n     */\r\n    public JSONWriter(Writer w) {\r\n        this.comma = false;\r\n        this.mode = 'i';\r\n        this.stack = new JSONObject[maxdepth];\r\n        this.top = 0;\r\n        this.writer = w;\r\n    }\r\n\r\n    /**\r\n     * Append a value.\r\n     * @param string A string value.\r\n     * @return this\r\n     * @throws JSONException If the value is out of sequence.\r\n     */\r\n    private JSONWriter append(String string) throws JSONException {\r\n        if (string == null) {\r\n            throw new JSONException(\"Null pointer\");\r\n        }\r\n        if (this.mode == 'o' || this.mode == 'a') {\r\n            try {\r\n                if (this.comma && this.mode == 'a') {\r\n                    this.writer.write(',');\r\n                }\r\n                this.writer.write(string);\r\n            } catch (IOException e) {\r\n                throw new JSONException(e);\r\n            }\r\n            if (this.mode == 'o') {\r\n                this.mode = 'k';\r\n            }\r\n            this.comma = true;\r\n            return this;\r\n        }\r\n        throw new JSONException(\"Value out of sequence.\");\r\n    }\r\n\r\n    /**\r\n     * Begin appending a new array. All values until the balancing\r\n     * <code>endArray</code> will be appended to this array. The\r\n     * <code>endArray</code> method must be called to mark the array's end.\r\n     * @return this\r\n     * @throws JSONException If the nesting is too deep, or if the object is\r\n     * started in the wrong place (for example as a key or after the end of the\r\n     * outermost array or object).\r\n     */\r\n    public JSONWriter array() throws JSONException {\r\n        if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {\r\n            this.push(null);\r\n            this.append(\"[\");\r\n            this.comma = false;\r\n            return this;\r\n        }\r\n        throw new JSONException(\"Misplaced array.\");\r\n    }\r\n\r\n    /**\r\n     * End something.\r\n     * @param mode Mode\r\n     * @param c Closing character\r\n     * @return this\r\n     * @throws JSONException If unbalanced.\r\n     */\r\n    private JSONWriter end(char mode, char c) throws JSONException {\r\n        if (this.mode != mode) {\r\n            throw new JSONException(mode == 'a' ? \"Misplaced endArray.\" : \r\n            \t\t\"Misplaced endObject.\");\r\n        }\r\n        this.pop(mode);\r\n        try {\r\n            this.writer.write(c);\r\n        } catch (IOException e) {\r\n            throw new JSONException(e);\r\n        }\r\n        this.comma = true;\r\n        return this;\r\n    }\r\n\r\n    /**\r\n     * End an array. This method most be called to balance calls to\r\n     * <code>array</code>.\r\n     * @return this\r\n     * @throws JSONException If incorrectly nested.\r\n     */\r\n    public JSONWriter endArray() throws JSONException {\r\n        return this.end('a', ']');\r\n    }\r\n\r\n    /**\r\n     * End an object. This method most be called to balance calls to\r\n     * <code>object</code>.\r\n     * @return this\r\n     * @throws JSONException If incorrectly nested.\r\n     */\r\n    public JSONWriter endObject() throws JSONException {\r\n        return this.end('k', '}');\r\n    }\r\n\r\n    /**\r\n     * Append a key. The key will be associated with the next value. In an\r\n     * object, every value must be preceded by a key.\r\n     * @param string A key string.\r\n     * @return this\r\n     * @throws JSONException If the key is out of place. For example, keys\r\n     *  do not belong in arrays or if the key is null.\r\n     */\r\n    public JSONWriter key(String string) throws JSONException {\r\n        if (string == null) {\r\n            throw new JSONException(\"Null key.\");\r\n        }\r\n        if (this.mode == 'k') {\r\n            try {\r\n                stack[top - 1].putOnce(string, Boolean.TRUE);\r\n                if (this.comma) {\r\n                    this.writer.write(',');\r\n                }\r\n                this.writer.write(JSONObject.quote(string));\r\n                this.writer.write(':');\r\n                this.comma = false;\r\n                this.mode = 'o';\r\n                return this;\r\n            } catch (IOException e) {\r\n                throw new JSONException(e);\r\n            }\r\n        }\r\n        throw new JSONException(\"Misplaced key.\");\r\n    }\r\n\r\n\r\n    /**\r\n     * Begin appending a new object. All keys and values until the balancing\r\n     * <code>endObject</code> will be appended to this object. The\r\n     * <code>endObject</code> method must be called to mark the object's end.\r\n     * @return this\r\n     * @throws JSONException If the nesting is too deep, or if the object is\r\n     * started in the wrong place (for example as a key or after the end of the\r\n     * outermost array or object).\r\n     */\r\n    public JSONWriter object() throws JSONException {\r\n        if (this.mode == 'i') {\r\n            this.mode = 'o';\r\n        }\r\n        if (this.mode == 'o' || this.mode == 'a') {\r\n            this.append(\"{\");\r\n            this.push(new JSONObject());\r\n            this.comma = false;\r\n            return this;\r\n        }\r\n        throw new JSONException(\"Misplaced object.\");\r\n\r\n    }\r\n\r\n\r\n    /**\r\n     * Pop an array or object scope.\r\n     * @param c The scope to close.\r\n     * @throws JSONException If nesting is wrong.\r\n     */\r\n    private void pop(char c) throws JSONException {\r\n        if (this.top <= 0) {\r\n            throw new JSONException(\"Nesting error.\");\r\n        }\r\n        char m = this.stack[this.top - 1] == null ? 'a' : 'k';\r\n        if (m != c) {\r\n            throw new JSONException(\"Nesting error.\");\r\n        }\r\n        this.top -= 1;\r\n        this.mode = this.top == 0 ? \r\n        \t\t'd' : this.stack[this.top - 1] == null ? 'a' : 'k';\r\n    }\r\n\r\n    /**\r\n     * Push an array or object scope.\r\n     * @param c The scope to open.\r\n     * @throws JSONException If nesting is too deep.\r\n     */\r\n    private void push(JSONObject jo) throws JSONException {\r\n        if (this.top >= maxdepth) {\r\n            throw new JSONException(\"Nesting too deep.\");\r\n        }\r\n        this.stack[this.top] = jo;\r\n        this.mode = jo == null ? 'a' : 'k';\r\n        this.top += 1;\r\n    }\r\n\r\n\r\n    /**\r\n     * Append either the value <code>true</code> or the value\r\n     * <code>false</code>.\r\n     * @param b A boolean.\r\n     * @return this\r\n     * @throws JSONException\r\n     */\r\n    public JSONWriter value(boolean b) throws JSONException {\r\n        return this.append(b ? \"true\" : \"false\");\r\n    }\r\n\r\n    /**\r\n     * Append a double value.\r\n     * @param d A double.\r\n     * @return this\r\n     * @throws JSONException If the number is not finite.\r\n     */\r\n    public JSONWriter value(double d) throws JSONException {\r\n        return this.value(new Double(d));\r\n    }\r\n\r\n    /**\r\n     * Append a long value.\r\n     * @param l A long.\r\n     * @return this\r\n     * @throws JSONException\r\n     */\r\n    public JSONWriter value(long l) throws JSONException {\r\n        return this.append(Long.toString(l));\r\n    }\r\n\r\n\r\n    /**\r\n     * Append an object value.\r\n     * @param object The object to append. It can be null, or a Boolean, Number,\r\n     *   String, JSONObject, or JSONArray, or an object that implements JSONString.\r\n     * @return this\r\n     * @throws JSONException If the value is out of sequence.\r\n     */\r\n    public JSONWriter value(Object object) throws JSONException {\r\n        return this.append(JSONObject.valueToString(object));\r\n    }\r\n}\r\n"
  }
]