diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
new file mode 100644
index 000000000..df4bf7981
--- /dev/null
+++ b/.github/workflows/codeql-analysis.yml
@@ -0,0 +1,43 @@
+name: "CodeQL"
+
+on:
+ push:
+ branches: [ master ]
+ pull_request:
+ # The branches below must be a subset of the branches above
+ branches: [ master ]
+ schedule:
+ - cron: '18 18 * * 1'
+
+jobs:
+ analyze:
+ name: Analyze
+ runs-on: ubuntu-latest
+ permissions:
+ actions: read
+ contents: read
+ security-events: write
+
+ strategy:
+ fail-fast: false
+ matrix:
+ language: [ 'java' ]
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+
+ # Initializes the CodeQL tools for scanning.
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@v2
+ with:
+ languages: ${{ matrix.language }}
+ # If you wish to specify custom queries, you can do so here or in a config file.
+ # By default, queries listed here will override any specified in a config file.
+ # Prefix the list here with "+" to use these queries and those in the config file.
+ # queries: ./path/to/local/query, your-org/your-repo/queries@main
+
+ - run: "mvn clean compile -Dmaven.test.skip=true -Dmaven.site.skip=true -Dmaven.javadoc.skip=true"
+
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@v2
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
new file mode 100644
index 000000000..d59702cae
--- /dev/null
+++ b/.github/workflows/pipeline.yml
@@ -0,0 +1,228 @@
+# This workflow will build a Java project with Maven
+# For more information see: https://docs.github.com/en/actions/learn-github-actions or https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions
+
+name: Java CI with Maven
+
+on:
+ push:
+ # branches: [ master ]
+ pull_request:
+ branches: [ master ]
+
+jobs:
+ # old-school build and jar method. No tests run or compiled.
+ build-1_6:
+ name: Java 1.6
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Setup java
+ uses: actions/setup-java@v1
+ with:
+ java-version: 1.6
+ - name: Compile Java 1.6
+ run: |
+ mkdir -p target/classes
+ javac -version
+ javac -source 1.6 -target 1.6 -d target/classes/ src/main/java/org/json/*.java
+ - name: Create java 1.6 JAR
+ run: |
+ jar cvf target/org.json.jar -C target/classes .
+ - name: Upload JAR 1.6
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Create java 1.6 JAR
+ path: target/*.jar
+
+ build-8:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ max-parallel: 1
+ matrix:
+ # build against supported Java LTS versions:
+ java: [ 8 ]
+ name: Java ${{ matrix.java }}
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v3
+ with:
+ distribution: 'temurin'
+ java-version: ${{ matrix.java }}
+ cache: 'maven'
+ - name: Compile Java ${{ matrix.java }}
+ run: mvn clean compile -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true -D maven.javadoc.skip=true
+ - name: Run Tests ${{ matrix.java }}
+ run: |
+ mvn test -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ - name: Build Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ run: |
+ mvn surefire-report:report-only -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ mvn site -D generateReports=false -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ - name: Upload Test Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Test Report ${{ matrix.java }}
+ path: target/site/
+ - name: Package Jar ${{ matrix.java }}
+ run: mvn clean package -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true
+ - name: Upload Package Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Package Jar ${{ matrix.java }}
+ path: target/*.jar
+
+ build-11:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ max-parallel: 1
+ matrix:
+ # build against supported Java LTS versions:
+ java: [ 11 ]
+ name: Java ${{ matrix.java }}
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v3
+ with:
+ distribution: 'temurin'
+ java-version: ${{ matrix.java }}
+ cache: 'maven'
+ - name: Compile Java ${{ matrix.java }}
+ run: mvn clean compile -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true -D maven.javadoc.skip=true
+ - name: Run Tests ${{ matrix.java }}
+ run: |
+ mvn test -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ - name: Build Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ run: |
+ mvn surefire-report:report-only -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ mvn site -D generateReports=false -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ - name: Upload Test Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Test Report ${{ matrix.java }}
+ path: target/site/
+ - name: Package Jar ${{ matrix.java }}
+ run: mvn clean package -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true
+ - name: Upload Package Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Package Jar ${{ matrix.java }}
+ path: target/*.jar
+
+ build-17:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ max-parallel: 1
+ matrix:
+ # build against supported Java LTS versions:
+ java: [ 17 ]
+ name: Java ${{ matrix.java }}
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v3
+ with:
+ distribution: 'temurin'
+ java-version: ${{ matrix.java }}
+ cache: 'maven'
+ - name: Compile Java ${{ matrix.java }}
+ run: mvn clean compile -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true -D maven.javadoc.skip=true
+ - name: Run Tests ${{ matrix.java }}
+ run: |
+ mvn test -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ - name: Build Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ run: |
+ mvn surefire-report:report-only -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ mvn site -D generateReports=false -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ - name: Upload Test Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Test Report ${{ matrix.java }}
+ path: target/site/
+ - name: Package Jar ${{ matrix.java }}
+ run: mvn clean package -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true
+ - name: Upload Package Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Package Jar ${{ matrix.java }}
+ path: target/*.jar
+
+ build-21:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ max-parallel: 1
+ matrix:
+ # build against supported Java LTS versions:
+ java: [ 21 ]
+ name: Java ${{ matrix.java }}
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v3
+ with:
+ distribution: 'temurin'
+ java-version: ${{ matrix.java }}
+ cache: 'maven'
+ - name: Compile Java ${{ matrix.java }}
+ run: mvn clean compile -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true -D maven.javadoc.skip=true
+ - name: Run Tests ${{ matrix.java }}
+ run: |
+ mvn test -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ - name: Build Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ run: |
+ mvn surefire-report:report-only -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ mvn site -D generateReports=false -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }}
+ - name: Upload Test Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Test Report ${{ matrix.java }}
+ path: target/site/
+ - name: Package Jar ${{ matrix.java }}
+ run: mvn clean package -D maven.compiler.source=${{ matrix.java }} -D maven.compiler.target=${{ matrix.java }} -D maven.test.skip=true -D maven.site.skip=true
+ - name: Upload Package Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: Package Jar ${{ matrix.java }}
+ path: target/*.jar
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..b78af4db7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,18 @@
+# ignore eclipse project files
+.project
+.classpath
+# ignore vscode files
+.vscode
+# ignore Intellij Idea project files
+.idea
+*.iml
+/target/
+
+/bin/
+build
+.settings/
+/.gradle/
+/gradle/
+/gradlew
+/gradlew.bat
+.gitmodules
diff --git a/CDL.java b/CDL.java
deleted file mode 100755
index 0fc3cf828..000000000
--- a/CDL.java
+++ /dev/null
@@ -1,279 +0,0 @@
-package org.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * This provides static methods to convert comma delimited text into a
- * JSONArray, and to covert a JSONArray into comma delimited text. Comma
- * delimited text is a very popular format for data interchange. It is
- * understood by most database, spreadsheet, and organizer programs.
- *
- * Each row of text represents a row in a table or a data record. Each row
- * ends with a NEWLINE character. Each row contains one or more values.
- * Values are separated by commas. A value can contain any character except
- * for comma, unless is is wrapped in single quotes or double quotes.
- *
- * The first row usually contains the names of the columns.
- *
- * A comma delimited list can be converted into a JSONArray of JSONObjects.
- * The names for the elements in the JSONObjects can be taken from the names
- * in the first row.
- * @author JSON.org
- * @version 2012-11-13
- */
-public class CDL {
-
- /**
- * Get the next value. The value can be wrapped in quotes. The value can
- * be empty.
- * @param x A JSONTokener of the source text.
- * @return The value string, or null if empty.
- * @throws JSONException if the quoted string is badly formed.
- */
- private static String getValue(JSONTokener x) throws JSONException {
- char c;
- char q;
- StringBuffer sb;
- do {
- c = x.next();
- } while (c == ' ' || c == '\t');
- switch (c) {
- case 0:
- return null;
- case '"':
- case '\'':
- q = c;
- sb = new StringBuffer();
- for (;;) {
- c = x.next();
- if (c == q) {
- break;
- }
- if (c == 0 || c == '\n' || c == '\r') {
- throw x.syntaxError("Missing close quote '" + q + "'.");
- }
- sb.append(c);
- }
- return sb.toString();
- case ',':
- x.back();
- return "";
- default:
- x.back();
- return x.nextTo(',');
- }
- }
-
- /**
- * Produce a JSONArray of strings from a row of comma delimited values.
- * @param x A JSONTokener of the source text.
- * @return A JSONArray of strings.
- * @throws JSONException
- */
- public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
- JSONArray ja = new JSONArray();
- for (;;) {
- String value = getValue(x);
- char c = x.next();
- if (value == null ||
- (ja.length() == 0 && value.length() == 0 && c != ',')) {
- return null;
- }
- ja.put(value);
- for (;;) {
- if (c == ',') {
- break;
- }
- if (c != ' ') {
- if (c == '\n' || c == '\r' || c == 0) {
- return ja;
- }
- throw x.syntaxError("Bad character '" + c + "' (" +
- (int)c + ").");
- }
- c = x.next();
- }
- }
- }
-
- /**
- * Produce a JSONObject from a row of comma delimited text, using a
- * parallel JSONArray of strings to provides the names of the elements.
- * @param names A JSONArray of names. This is commonly obtained from the
- * first row of a comma delimited text file using the rowToJSONArray
- * method.
- * @param x A JSONTokener of the source text.
- * @return A JSONObject combining the names and values.
- * @throws JSONException
- */
- public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
- throws JSONException {
- JSONArray ja = rowToJSONArray(x);
- return ja != null ? ja.toJSONObject(names) : null;
- }
-
- /**
- * Produce a comma delimited text row from a JSONArray. Values containing
- * the comma character will be quoted. Troublesome characters may be
- * removed.
- * @param ja A JSONArray of strings.
- * @return A string ending in NEWLINE.
- */
- public static String rowToString(JSONArray ja) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < ja.length(); i += 1) {
- if (i > 0) {
- sb.append(',');
- }
- Object object = ja.opt(i);
- if (object != null) {
- String string = object.toString();
- if (string.length() > 0 && (string.indexOf(',') >= 0 ||
- string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
- string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
- sb.append('"');
- int length = string.length();
- for (int j = 0; j < length; j += 1) {
- char c = string.charAt(j);
- if (c >= ' ' && c != '"') {
- sb.append(c);
- }
- }
- sb.append('"');
- } else {
- sb.append(string);
- }
- }
- }
- sb.append('\n');
- return sb.toString();
- }
-
- /**
- * Produce a JSONArray of JSONObjects from a comma delimited text string,
- * using the first row as a source of names.
- * @param string The comma delimited text.
- * @return A JSONArray of JSONObjects.
- * @throws JSONException
- */
- public static JSONArray toJSONArray(String string) throws JSONException {
- return toJSONArray(new JSONTokener(string));
- }
-
- /**
- * Produce a JSONArray of JSONObjects from a comma delimited text string,
- * using the first row as a source of names.
- * @param x The JSONTokener containing the comma delimited text.
- * @return A JSONArray of JSONObjects.
- * @throws JSONException
- */
- public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
- return toJSONArray(rowToJSONArray(x), x);
- }
-
- /**
- * Produce a JSONArray of JSONObjects from a comma delimited text string
- * using a supplied JSONArray as the source of element names.
- * @param names A JSONArray of strings.
- * @param string The comma delimited text.
- * @return A JSONArray of JSONObjects.
- * @throws JSONException
- */
- public static JSONArray toJSONArray(JSONArray names, String string)
- throws JSONException {
- return toJSONArray(names, new JSONTokener(string));
- }
-
- /**
- * Produce a JSONArray of JSONObjects from a comma delimited text string
- * using a supplied JSONArray as the source of element names.
- * @param names A JSONArray of strings.
- * @param x A JSONTokener of the source text.
- * @return A JSONArray of JSONObjects.
- * @throws JSONException
- */
- public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
- throws JSONException {
- if (names == null || names.length() == 0) {
- return null;
- }
- JSONArray ja = new JSONArray();
- for (;;) {
- JSONObject jo = rowToJSONObject(names, x);
- if (jo == null) {
- break;
- }
- ja.put(jo);
- }
- if (ja.length() == 0) {
- return null;
- }
- return ja;
- }
-
-
- /**
- * Produce a comma delimited text from a JSONArray of JSONObjects. The
- * first row will be a list of names obtained by inspecting the first
- * JSONObject.
- * @param ja A JSONArray of JSONObjects.
- * @return A comma delimited text.
- * @throws JSONException
- */
- public static String toString(JSONArray ja) throws JSONException {
- JSONObject jo = ja.optJSONObject(0);
- if (jo != null) {
- JSONArray names = jo.names();
- if (names != null) {
- return rowToString(names) + toString(names, ja);
- }
- }
- return null;
- }
-
- /**
- * Produce a comma delimited text from a JSONArray of JSONObjects using
- * a provided list of names. The list of names is not included in the
- * output.
- * @param names A JSONArray of strings.
- * @param ja A JSONArray of JSONObjects.
- * @return A comma delimited text.
- * @throws JSONException
- */
- public static String toString(JSONArray names, JSONArray ja)
- throws JSONException {
- if (names == null || names.length() == 0) {
- return null;
- }
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < ja.length(); i += 1) {
- JSONObject jo = ja.optJSONObject(i);
- if (jo != null) {
- sb.append(rowToString(jo.toJSONArray(names)));
- }
- }
- return sb.toString();
- }
-}
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 000000000..ecd775579
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,76 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, sex characteristics, gender identity and expression,
+level of experience, education, socio-economic status, nationality, personal
+appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+ advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+ address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at jsonjava060@gmail.com. All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+
+[homepage]: https://www.contributor-covenant.org
+
+For answers to common questions about this code of conduct, see
+https://www.contributor-covenant.org/faq
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 000000000..8102dcf63
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,22 @@
+# Contribution Guidelines
+
+Feel free to work on any open issue, you don't need to ask permission first. This year, the hacktoberfest label will be added to any PR and associated issue during the month of October.
+
+If you discover an issue you would like to work on, you can add a new issue to the list. If it meets our criteria, it will be available to work on (if not, it will be closed after review).
+
+# Who is allowed to submit pull requests for this project?
+
+Anyone can submit pull requests for code, tests, or documentation.
+
+# How do you decide which pull requests to accept?
+
+* Does it call out a bug that needs to be fixed? If so, it goes to the top of the list.
+* Does it fix a major user inconvenience? These are given high priority as well.
+* Does it align with the specs? If not, it will probably not be accepted. It turns out there are gray areas in the specs. If this is in a gray area, it will likely be given the benefit of the doubt.
+* Does it break the existing behavior of the lib? If so, it will not be accepted, unless it fixes an egregious bug. This is happening less frequently now.
+
+# For more guidance, see these links:
+
+[README.md (includes build instructions)](https://github.com/stleary/JSON-java#readme)
+
+[FAQ - all your questions answered](https://github.com/stleary/JSON-java/wiki/FAQ)
diff --git a/Cookie.java b/Cookie.java
deleted file mode 100755
index 9cf5ce2c5..000000000
--- a/Cookie.java
+++ /dev/null
@@ -1,169 +0,0 @@
-package org.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * Convert a web browser cookie specification to a JSONObject and back.
- * JSON and Cookies are both notations for name/value pairs.
- * @author JSON.org
- * @version 2010-12-24
- */
-public class Cookie {
-
- /**
- * Produce a copy of a string in which the characters '+', '%', '=', ';'
- * and control characters are replaced with "%hh". This is a gentle form
- * of URL encoding, attempting to cause as little distortion to the
- * string as possible. The characters '=' and ';' are meta characters in
- * cookies. By convention, they are escaped using the URL-encoding. This is
- * only a convention, not a standard. Often, cookies are expected to have
- * encoded values. We encode '=' and ';' because we must. We encode '%' and
- * '+' because they are meta characters in URL encoding.
- * @param string The source string.
- * @return The escaped result.
- */
- public static String escape(String string) {
- char c;
- String s = string.trim();
- StringBuffer sb = new StringBuffer();
- int length = s.length();
- for (int i = 0; i < length; i += 1) {
- c = s.charAt(i);
- if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
- sb.append('%');
- sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
- sb.append(Character.forDigit((char)(c & 0x0f), 16));
- } else {
- sb.append(c);
- }
- }
- return sb.toString();
- }
-
-
- /**
- * Convert a cookie specification string into a JSONObject. The string
- * will contain a name value pair separated by '='. The name and the value
- * will be unescaped, possibly converting '+' and '%' sequences. The
- * cookie properties may follow, separated by ';', also represented as
- * name=value (except the secure property, which does not have a value).
- * The name will be stored under the key "name", and the value will be
- * stored under the key "value". This method does not do checking or
- * validation of the parameters. It only converts the cookie string into
- * a JSONObject.
- * @param string The cookie specification string.
- * @return A JSONObject containing "name", "value", and possibly other
- * members.
- * @throws JSONException
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- String name;
- JSONObject jo = new JSONObject();
- Object value;
- JSONTokener x = new JSONTokener(string);
- jo.put("name", x.nextTo('='));
- x.next('=');
- jo.put("value", x.nextTo(';'));
- x.next();
- while (x.more()) {
- name = unescape(x.nextTo("=;"));
- if (x.next() != '=') {
- if (name.equals("secure")) {
- value = Boolean.TRUE;
- } else {
- throw x.syntaxError("Missing '=' in cookie parameter.");
- }
- } else {
- value = unescape(x.nextTo(';'));
- x.next();
- }
- jo.put(name, value);
- }
- return jo;
- }
-
-
- /**
- * Convert a JSONObject into a cookie specification string. The JSONObject
- * must contain "name" and "value" members.
- * If the JSONObject contains "expires", "domain", "path", or "secure"
- * members, they will be appended to the cookie specification string.
- * All other members are ignored.
- * @param jo A JSONObject
- * @return A cookie specification string
- * @throws JSONException
- */
- public static String toString(JSONObject jo) throws JSONException {
- StringBuffer sb = new StringBuffer();
-
- sb.append(escape(jo.getString("name")));
- sb.append("=");
- sb.append(escape(jo.getString("value")));
- if (jo.has("expires")) {
- sb.append(";expires=");
- sb.append(jo.getString("expires"));
- }
- if (jo.has("domain")) {
- sb.append(";domain=");
- sb.append(escape(jo.getString("domain")));
- }
- if (jo.has("path")) {
- sb.append(";path=");
- sb.append(escape(jo.getString("path")));
- }
- if (jo.optBoolean("secure")) {
- sb.append(";secure");
- }
- return sb.toString();
- }
-
- /**
- * Convert %hh sequences to single characters, and
- * convert plus to space.
- * @param string A string that may contain
- * + (plus) and
- * %hh sequences.
- * @return The unescaped string.
- */
- public static String unescape(String string) {
- int length = string.length();
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < length; ++i) {
- char c = string.charAt(i);
- if (c == '+') {
- c = ' ';
- } else if (c == '%' && i + 2 < length) {
- int d = JSONTokener.dehexchar(string.charAt(i + 1));
- int e = JSONTokener.dehexchar(string.charAt(i + 2));
- if (d >= 0 && e >= 0) {
- c = (char)(d * 16 + e);
- i += 2;
- }
- }
- sb.append(c);
- }
- return sb.toString();
- }
-}
diff --git a/CookieList.java b/CookieList.java
deleted file mode 100755
index 7f4fe0751..000000000
--- a/CookieList.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package org.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.util.Iterator;
-
-/**
- * Convert a web browser cookie list string to a JSONObject and back.
- * @author JSON.org
- * @version 2010-12-24
- */
-public class CookieList {
-
- /**
- * Convert a cookie list into a JSONObject. A cookie list is a sequence
- * of name/value pairs. The names are separated from the values by '='.
- * The pairs are separated by ';'. The names and the values
- * will be unescaped, possibly converting '+' and '%' sequences.
- *
- * To add a cookie to a cooklist,
- * cookielistJSONObject.put(cookieJSONObject.getString("name"),
- * cookieJSONObject.getString("value"));
- * @param string A cookie list string
- * @return A JSONObject
- * @throws JSONException
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- JSONObject jo = new JSONObject();
- JSONTokener x = new JSONTokener(string);
- while (x.more()) {
- String name = Cookie.unescape(x.nextTo('='));
- x.next('=');
- jo.put(name, Cookie.unescape(x.nextTo(';')));
- x.next();
- }
- return jo;
- }
-
-
- /**
- * Convert a JSONObject into a cookie list. A cookie list is a sequence
- * of name/value pairs. The names are separated from the values by '='.
- * The pairs are separated by ';'. The characters '%', '+', '=', and ';'
- * in the names and values are replaced by "%hh".
- * @param jo A JSONObject
- * @return A cookie list string
- * @throws JSONException
- */
- public static String toString(JSONObject jo) throws JSONException {
- boolean b = false;
- Iterator keys = jo.keys();
- String string;
- StringBuffer sb = new StringBuffer();
- while (keys.hasNext()) {
- string = keys.next().toString();
- if (!jo.isNull(string)) {
- if (b) {
- sb.append(';');
- }
- sb.append(Cookie.escape(string));
- sb.append("=");
- sb.append(Cookie.escape(jo.getString(string)));
- b = true;
- }
- }
- return sb.toString();
- }
-}
diff --git a/Examples.md b/Examples.md
new file mode 100644
index 000000000..fb010d5dc
--- /dev/null
+++ b/Examples.md
@@ -0,0 +1,433 @@
+
This document's intention is to explain to new-comers the basics of this project
+
+
+
Part 1: Creating a JSON document
+
+
Using JSONArray
+
+```java
+private static void JSONExampleArray1() {
+ //We create a JSONObject from a String containing an array using JSONArray
+ //Firstly, we declare an Array in a String
+
+ String arrayStr =
+ "["+"true,"+"false,"+ "\"true\","+ "\"false\","+"\"hello\","+"23.45e-4,"+
+ "\"23.45\","+"42,"+"\"43\","+"["+"\"world\""+"],"+
+ "{"+
+ "\"key1\":\"value1\","+
+ "\"key2\":\"value2\","+
+ "\"key3\":\"value3\","+
+ "\"key4\":\"value4\""+
+ "},"+
+ "0,"+"\"-1\""+
+ "]";
+
+ //Then, we initializate the JSONArray thanks to its constructor
+
+ JSONArray array = new JSONArray(arrayStr);
+ System.out.println("Values array: "+ array);
+
+ //We convert that array into a JSONObject, but first, we need the labels, so we need another JSONArray with the labels.
+ //Here we will use an auxiliary function to get one for the example.
+
+ JSONArray list = listNumberArray(array.length());
+ System.out.println("Label Array: "+ list.toString());
+ //Now, we construct the JSONObject using both the value array and the label array.
+ JSONObject object = array.toJSONObject(list);
+ System.out.println("Final JSONOBject: " + object);
+}
+
+//This method creates an JSONArray of labels in which those are generated by their positions
+
+private static JSONArray listNumberArray(int max){
+ JSONArray res = new JSONArray();
+ for (int i=0; iUsing JSONStringer
+
+```java
+private static void JSONExampleStringer() {
+
+ //We initializate the JSONStringer
+
+ JSONStringer jsonStringer = new JSONStringer();
+
+ //Now we start the process of adding elements with .object()
+
+ jsonStringer.object();
+
+ //We can now add elements as keys and values with .values () and .key()
+
+ jsonStringer.key("trueValue").value(true);
+ jsonStringer.key("falseValue").value(false);
+ jsonStringer.key("nullValue").value(null);
+ jsonStringer.key("stringValue").value("hello world!");
+ jsonStringer.key("complexStringValue").value("h\be\tllo w\u1234orld!");
+ jsonStringer.key("intValue").value(42);
+ jsonStringer.key("doubleValue").value(-23.45e67);
+
+ //We end this prcedure with .ednObject
+
+ jsonStringer.endObject();
+
+ //Once we have a JSONStringer, we convert it to JSONObject generating a String and using JSONObject's contructor.
+
+ String str = jsonStringer.toString();
+ JSONObject jsonObject = new JSONObject(str);
+
+ System.out.println("Final JSONOBject: " + jsonObject);
+}
+```
+
Using JSONObject
+
+```java
+private static void JSONExampleObject1() {
+
+ //We can create a JSONObject from a String with the class builder
+
+ String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}";
+ JSONObject example = new JSONObject(string);
+ System.out.println("Final JSONObject: " + example);
+
+}
+```
+```java
+private static void JSONExampleObject2() {
+
+ //We can also create a JSONObject directly without messing around with any of the other functions.
+
+ JSONObject example = new JSONObject();
+
+
+ //Now we add the keys and values in a similar way as the Stringer method
+ example.put("key", "value");
+
+ //As you can see, the first entry is the key and the second would be its associeted value.
+
+ example.put("key2", 5);
+ example.put("key3", -23.45e67);
+ example.put("trueValue", true);
+
+ //We can't add null values thougth
+
+ //example.put("nullValue", null); //This is not possible
+
+ System.out.println("Final JSONOBject: " + example);
+}
+```
+```java
+private static void JSONExampleObject3() {
+
+ //We can also create a JSONObject with a Java Map
+ //YoU will need a Map whose keys are Strings. The values can be whatever you want
+
+ Map map = new HashMap();
+
+ map.put("key1", 1.0);
+ map.put("key2", -23.45e67);
+
+ //We create the JSONObject with the map with its class builder
+
+ JSONObject example = new JSONObject(map);
+ System.out.println("Final JSONOBject: " + example);
+}
+```
+
Using JSONWriter
+
+```java
+private static void JSONExamplWriter() {
+
+ //This method works in a very similar way to Object and Stringer in the construction of the JSON.
+ //The difference is that it needs a Java object called "Appendable" like StringBuilder
+
+ StringBuilder write = new StringBuilder();
+ JSONWriter jsonWriter = new JSONWriter(write);
+
+ //We behave now the same way as Stringer
+
+ jsonWriter.object();
+
+ jsonWriter.key("trueValue").value(true);
+ jsonWriter.key("falseValue").value(false);
+ jsonWriter.key("nullValue").value(null);
+ jsonWriter.key("stringValue").value("hello world!");
+ jsonWriter.key("complexStringValue").value("h\be\tllo w\u1234orld!");
+ jsonWriter.key("intValue").value(42);
+ jsonWriter.key("doubleValue").value(-23.45e67);
+
+ jsonWriter.endObject();
+
+ //The resoult should be in the "write" object
+
+ System.out.println("JSON: " + write.toString());
+
+ //The difference is that we don't get a JSONObject in this one.
+
+
+}
+```
+```java
+private static void JSONExampleTokener() {
+
+ //A partir de una String podemos crear un JSONTokener, que lo podemos usar alternativamente para JSONArray,JSONObject
+
+ String string = "this is not a valid JSON string";
+ JSONTokener token = new JSONTokener(string);
+
+ //Now you can use the token in JSONObject and Array the same way as a String
+
+ JSONObject object = new JSONObject(token);
+ JSONArray array = new JSONArray(token);
+
+}
+```
+
Part 2: Conversion methods
+
We don't need to have a JSON document to work. This project also admits conversions from other type of files.
+
Secondly, we can also convert from JSON to those type of files.
+
+
Extra: Conversion to JSONArray
+
+```java
+private static void JSONObjectToArray() {
+ //We start with a JSONObject
+
+ String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}";
+
+ JSONObject example = new JSONObject(string);
+
+ //We need a list of key strings like the reverse operation
+
+ JSONArray keyStrings = listNumberArray(example.length());
+
+ //Then we convert to the Array using both elelements
+
+ JSONArray array = example.toJSONArray(keyStrings);
+
+ System.out.println("Final JSONArray: " + array);
+}
+```
+
XML Conversions
+
+```java
+private static void XMLToExampleConversion() {
+
+ //We start with a JSONObject
+
+ String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}";
+ JSONObject example = new JSONObject(string);
+
+ //We obtain a String with XML format with toString()
+
+ String output = XML.toString(example);
+ System.out.println("Final XML: " + output);
+}
+```
+```java
+private static void XMLFromExampleConversion() {
+
+ //We start with a string with the XML format
+
+ String string = "<0>value0><1>51><2>-2.345E+682><3>true3>";
+
+ //We obtain a JSONObject with toJSONOBject()
+
+ JSONObject output = XML.toJSONObject(string);
+
+ System.out.println("Final JSONObject: " + output);
+}
+```
+
Cookie Conversions
+
+```java
+private static void CookieToExampleConversion() {
+
+ //We start with a JSONObject
+ //The JSONOBject needs to entries that gives the cookie a name and gives the field "name" a name too.
+ //The Cokkie format doesn't support booleans
+
+ String string = "{\"name\":\"Cookie-Name\",\"value\":\"name\",\"1\":5,\"2\":-2.345E68,\"3\":'true'}";
+ JSONObject example = new JSONObject(string);
+
+ //We obtain a String with Cookie format with toString()
+
+ String output = Cookie.toString(example);
+ System.out.println("Final Cookie: " + output);
+}
+```
+```java
+private static void CookieFromExampleConversion() {
+
+ //We start with a string with the Cookie format
+
+ String string = "Cookie-Name=name;1=5;2=-2.345E%2b68;3=true";
+
+ //We obtain a JSONObject with toJSONOBject()
+
+ JSONObject output = Cookie.toJSONObject(string);
+ System.out.println("Final JSONObject: " + output);
+}
+```
+
+
HTTP Conversions
+
+```java
+private static void HTTPToExampleConversion() {
+
+ //We start with a JSONObject
+ //The JSONObject must have the minimun header for a HTTP request or header
+
+ String string = "{\"Method\":\"POST\",\"Request-URI\":'/',\"HTTP-Version\":'HTTP/1.1',\"Value1\":true,\"Value2\":2,\"Value3\":-2.345E68}";
+
+ JSONObject example = new JSONObject(string);
+
+ //We obtain a String with HTTP format with toString()
+
+ String output = HTTP.toString(example);
+ System.out.println("Final HTTP: " + output);
+}
+```
+```java
+private static void HTTPFromExampleConversion() {
+
+ //We start with a string with the HTTP format
+
+ String string = "Final HTTP: POST '/' HTTP/1.1 Value3: -2.345E+68 Value1: true Value2: 2";
+
+ //We obtain a JSONObject with toJSONOBject()
+
+ JSONObject output = HTTP.toJSONObject(string);
+ System.out.println("Final JSONObject: " + output);
+}
+```
+
CDL Conversions
+
+```java
+private static void CDLToExampleConversion() {
+
+ //We start with some JSONObjects with the same values in the keys but different values in the "values"
+
+ String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}";
+ JSONObject example = new JSONObject(string);
+
+ String string2 = "{\"0\":\"value2\",\"1\":6,\"2\":-8.345E68,\"3\":false}";
+ JSONObject example2 = new JSONObject(string2);
+
+ //We need now a JSONArray with those JSONObjects
+
+ JSONArray array = new JSONArray();
+ array.put(example);
+ array.put(example2);
+
+ //We obtain a String with XML format with toString()
+
+ String output = CDL.toString(array);
+ System.out.println("Final CDL: \r\n" + output);
+}
+```
+```java
+private static void CDLFromExampleConversion() {
+
+ //We start wtih a String with the CDL format
+
+ String string = "0,1,2,3\n"
+ + "value,5,-2.345E+68,true\n"
+ + "value2,6,-8.345E+68,false";
+
+ //We obtain a JSONArray with toJSONOBject()
+
+ JSONArray output = CDL.toJSONArray(string);
+ System.out.println("Final JSONArray: " + output);
+}
+```
+
Properties Conversions
+
+```java
+private static Properties PropertyToExampleConversion() {
+
+ //We start with a JSONObject
+
+ String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}";
+ JSONObject example = new JSONObject(string);
+
+ //We obtain a String with Properties format with toString()
+
+ Properties output = Property.toProperties(example);
+ System.out.println("Final Properties: " + output);
+
+ return output;
+}
+```
+```java
+private static void PropertyFromExampleConversion() {
+
+ //We start with a Properties object
+
+ Properties input = PropertyToExampleConversion();
+
+ //We obtain a JSONObject with toJSONOBject()
+
+ JSONObject output = Property.toJSONObject(input);
+ System.out.println("Final JSONObject: " + output);
+}
+```
+
List of all examples methods
+
+```java
+public static void main(String[] args) {
+ //JSONObjectToArray();
+ //JSONExampleArray1();
+ //JSONExampleArray2();
+ //JSONExampleStringer();
+ //JSONExampleObject1();
+ //JSONExampleObject2();
+ //JSONExampleObject3();
+ //JSONExamplWriter();
+ //XMLToExampleConversion();
+ //XMLFromExampleConversion();
+ //CookieToExampleConversion();
+ //CookieFromExampleConversion();
+ //HTTPToExampleConversion();
+ //HTTPFromExampleConversion();
+ //CDLToExampleConversion();
+ //CDLFromExampleConversion();
+ //PropertyToExampleConversion();
+ //PropertyFromExampleConversion();
+}
+```
+
diff --git a/JSONArray.java b/JSONArray.java
deleted file mode 100644
index 673a91927..000000000
--- a/JSONArray.java
+++ /dev/null
@@ -1,944 +0,0 @@
-package org.json;
-
-/*
- Copyright (c) 2002 JSON.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
-
- The Software shall be used for Good, not Evil.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE.
- */
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * A JSONArray is an ordered sequence of values. Its external text form is a
- * string wrapped in square brackets with commas separating the values. The
- * internal form is an object having get and opt
- * methods for accessing the values by index, and put methods for
- * adding or replacing values. The values can be any of these types:
- * Boolean, JSONArray, JSONObject,
- * Number, String, or the
- * JSONObject.NULL object.
- *
- * The constructor can convert a JSON text into a Java object. The
- * toString method converts to JSON text.
- *
- * A get method returns a value if one can be found, and throws an
- * exception if one cannot be found. An opt method returns a
- * default value instead of throwing an exception, and so is useful for
- * obtaining optional values.
- *
- * The generic get() and opt() methods return an
- * object which you can cast or query for type. There are also typed
- * get and opt methods that do type checking and type
- * coercion for you.
- *
- * The texts produced by the toString methods strictly conform to
- * JSON syntax rules. The constructors are more forgiving in the texts they will
- * accept:
- *
- *
An extra , (comma) may appear just
- * before the closing bracket.
- *
The null value will be inserted when there is ,
- * (comma) elision.
- *
Strings may be quoted with ' (single
- * quote).
- *
Strings do not need to be quoted at all if they do not begin with a quote
- * or single quote, and if they do not contain leading or trailing spaces, and
- * if they do not contain any of these characters:
- * { } [ ] / \ : , # and if they do not look like numbers and
- * if they are not the reserved words true, false, or
- * null.
- *
- *
- * @author JSON.org
- * @version 2013-04-18
- */
-public class JSONArray {
-
- /**
- * The arrayList where the JSONArray's properties are kept.
- */
- private final ArrayList myArrayList;
-
- /**
- * Construct an empty JSONArray.
- */
- public JSONArray() {
- this.myArrayList = new ArrayList();
- }
-
- /**
- * Construct a JSONArray from a JSONTokener.
- *
- * @param x
- * A JSONTokener
- * @throws JSONException
- * If there is a syntax error.
- */
- public JSONArray(JSONTokener x) throws JSONException {
- this();
- if (x.nextClean() != '[') {
- throw x.syntaxError("A JSONArray text must start with '['");
- }
- if (x.nextClean() != ']') {
- x.back();
- for (;;) {
- if (x.nextClean() == ',') {
- x.back();
- this.myArrayList.add(JSONObject.NULL);
- } else {
- x.back();
- this.myArrayList.add(x.nextValue());
- }
- switch (x.nextClean()) {
- case ',':
- if (x.nextClean() == ']') {
- return;
- }
- x.back();
- break;
- case ']':
- return;
- default:
- throw x.syntaxError("Expected a ',' or ']'");
- }
- }
- }
- }
-
- /**
- * Construct a JSONArray from a source JSON text.
- *
- * @param source
- * A string that begins with [ (left
- * bracket) and ends with ]
- * (right bracket).
- * @throws JSONException
- * If there is a syntax error.
- */
- public JSONArray(String source) throws JSONException {
- this(new JSONTokener(source));
- }
-
- /**
- * Construct a JSONArray from a Collection.
- *
- * @param collection
- * A Collection.
- */
- public JSONArray(Collection collection) {
- this.myArrayList = new ArrayList();
- if (collection != null) {
- Iterator iter = collection.iterator();
- while (iter.hasNext()) {
- this.myArrayList.add(JSONObject.wrap(iter.next()));
- }
- }
- }
-
- /**
- * Construct a JSONArray from an array
- *
- * @throws JSONException
- * If not an array.
- */
- public JSONArray(Object array) throws JSONException {
- this();
- if (array.getClass().isArray()) {
- int length = Array.getLength(array);
- for (int i = 0; i < length; i += 1) {
- this.put(JSONObject.wrap(Array.get(array, i)));
- }
- } else {
- throw new JSONException(
- "JSONArray initial value should be a string or collection or array.");
- }
- }
-
- /**
- * Get the object value associated with an index.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return An object value.
- * @throws JSONException
- * If there is no value for the index.
- */
- public Object get(int index) throws JSONException {
- Object object = this.opt(index);
- if (object == null) {
- throw new JSONException("JSONArray[" + index + "] not found.");
- }
- return object;
- }
-
- /**
- * Get the boolean value associated with an index. The string values "true"
- * and "false" are converted to boolean.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return The truth.
- * @throws JSONException
- * If there is no value for the index or if the value is not
- * convertible to boolean.
- */
- public boolean getBoolean(int index) throws JSONException {
- Object object = this.get(index);
- if (object.equals(Boolean.FALSE)
- || (object instanceof String && ((String) object)
- .equalsIgnoreCase("false"))) {
- return false;
- } else if (object.equals(Boolean.TRUE)
- || (object instanceof String && ((String) object)
- .equalsIgnoreCase("true"))) {
- return true;
- }
- throw new JSONException("JSONArray[" + index + "] is not a boolean.");
- }
-
- /**
- * Get the double value associated with an index.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException
- * If the key is not found or if the value cannot be converted
- * to a number.
- */
- public double getDouble(int index) throws JSONException {
- Object object = this.get(index);
- try {
- return object instanceof Number ? ((Number) object).doubleValue()
- : Double.parseDouble((String) object);
- } catch (Exception e) {
- throw new JSONException("JSONArray[" + index + "] is not a number.");
- }
- }
-
- /**
- * Get the int value associated with an index.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException
- * If the key is not found or if the value is not a number.
- */
- public int getInt(int index) throws JSONException {
- Object object = this.get(index);
- try {
- return object instanceof Number ? ((Number) object).intValue()
- : Integer.parseInt((String) object);
- } catch (Exception e) {
- throw new JSONException("JSONArray[" + index + "] is not a number.");
- }
- }
-
- /**
- * Get the JSONArray associated with an index.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return A JSONArray value.
- * @throws JSONException
- * If there is no value for the index. or if the value is not a
- * JSONArray
- */
- public JSONArray getJSONArray(int index) throws JSONException {
- Object object = this.get(index);
- if (object instanceof JSONArray) {
- return (JSONArray) object;
- }
- throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
- }
-
- /**
- * Get the JSONObject associated with an index.
- *
- * @param index
- * subscript
- * @return A JSONObject value.
- * @throws JSONException
- * If there is no value for the index or if the value is not a
- * JSONObject
- */
- public JSONObject getJSONObject(int index) throws JSONException {
- Object object = this.get(index);
- if (object instanceof JSONObject) {
- return (JSONObject) object;
- }
- throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
- }
-
- /**
- * Get the long value associated with an index.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException
- * If the key is not found or if the value cannot be converted
- * to a number.
- */
- public long getLong(int index) throws JSONException {
- Object object = this.get(index);
- try {
- return object instanceof Number ? ((Number) object).longValue()
- : Long.parseLong((String) object);
- } catch (Exception e) {
- throw new JSONException("JSONArray[" + index + "] is not a number.");
- }
- }
-
- /**
- * Get the string associated with an index.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return A string value.
- * @throws JSONException
- * If there is no string value for the index.
- */
- public String getString(int index) throws JSONException {
- Object object = this.get(index);
- if (object instanceof String) {
- return (String) object;
- }
- throw new JSONException("JSONArray[" + index + "] not a string.");
- }
-
- /**
- * Determine if the value is null.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return true if the value at the index is null, or if there is no value.
- */
- public boolean isNull(int index) {
- return JSONObject.NULL.equals(this.opt(index));
- }
-
- /**
- * Make a string from the contents of this JSONArray. The
- * separator string is inserted between each element. Warning:
- * This method assumes that the data structure is acyclical.
- *
- * @param separator
- * A string that will be inserted between the elements.
- * @return a string.
- * @throws JSONException
- * If the array contains an invalid number.
- */
- public String join(String separator) throws JSONException {
- int len = this.length();
- StringBuffer sb = new StringBuffer();
-
- for (int i = 0; i < len; i += 1) {
- if (i > 0) {
- sb.append(separator);
- }
- sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
- }
- return sb.toString();
- }
-
- /**
- * Get the number of elements in the JSONArray, included nulls.
- *
- * @return The length (or size).
- */
- public int length() {
- return this.myArrayList.size();
- }
-
- /**
- * Get the optional object value associated with an index.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return An object value, or null if there is no object at that index.
- */
- public Object opt(int index) {
- return (index < 0 || index >= this.length()) ? null : this.myArrayList
- .get(index);
- }
-
- /**
- * Get the optional boolean value associated with an index. It returns false
- * if there is no value at that index, or if the value is not Boolean.TRUE
- * or the String "true".
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return The truth.
- */
- public boolean optBoolean(int index) {
- return this.optBoolean(index, false);
- }
-
- /**
- * Get the optional boolean value associated with an index. It returns the
- * defaultValue if there is no value at that index or if it is not a Boolean
- * or the String "true" or "false" (case insensitive).
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @param defaultValue
- * A boolean default.
- * @return The truth.
- */
- public boolean optBoolean(int index, boolean defaultValue) {
- try {
- return this.getBoolean(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get the optional double value associated with an index. NaN is returned
- * if there is no value for the index, or if the value is not a number and
- * cannot be converted to a number.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return The value.
- */
- public double optDouble(int index) {
- return this.optDouble(index, Double.NaN);
- }
-
- /**
- * Get the optional double value associated with an index. The defaultValue
- * is returned if there is no value for the index, or if the value is not a
- * number and cannot be converted to a number.
- *
- * @param index
- * subscript
- * @param defaultValue
- * The default value.
- * @return The value.
- */
- public double optDouble(int index, double defaultValue) {
- try {
- return this.getDouble(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get the optional int value associated with an index. Zero is returned if
- * there is no value for the index, or if the value is not a number and
- * cannot be converted to a number.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return The value.
- */
- public int optInt(int index) {
- return this.optInt(index, 0);
- }
-
- /**
- * Get the optional int value associated with an index. The defaultValue is
- * returned if there is no value for the index, or if the value is not a
- * number and cannot be converted to a number.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @param defaultValue
- * The default value.
- * @return The value.
- */
- public int optInt(int index, int defaultValue) {
- try {
- return this.getInt(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get the optional JSONArray associated with an index.
- *
- * @param index
- * subscript
- * @return A JSONArray value, or null if the index has no value, or if the
- * value is not a JSONArray.
- */
- public JSONArray optJSONArray(int index) {
- Object o = this.opt(index);
- return o instanceof JSONArray ? (JSONArray) o : null;
- }
-
- /**
- * Get the optional JSONObject associated with an index. Null is returned if
- * the key is not found, or null if the index has no value, or if the value
- * is not a JSONObject.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return A JSONObject value.
- */
- public JSONObject optJSONObject(int index) {
- Object o = this.opt(index);
- return o instanceof JSONObject ? (JSONObject) o : null;
- }
-
- /**
- * Get the optional long value associated with an index. Zero is returned if
- * there is no value for the index, or if the value is not a number and
- * cannot be converted to a number.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return The value.
- */
- public long optLong(int index) {
- return this.optLong(index, 0);
- }
-
- /**
- * Get the optional long value associated with an index. The defaultValue is
- * returned if there is no value for the index, or if the value is not a
- * number and cannot be converted to a number.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @param defaultValue
- * The default value.
- * @return The value.
- */
- public long optLong(int index, long defaultValue) {
- try {
- return this.getLong(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get the optional string value associated with an index. It returns an
- * empty string if there is no value at that index. If the value is not a
- * string and is not null, then it is coverted to a string.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @return A String value.
- */
- public String optString(int index) {
- return this.optString(index, "");
- }
-
- /**
- * Get the optional string associated with an index. The defaultValue is
- * returned if the key is not found.
- *
- * @param index
- * The index must be between 0 and length() - 1.
- * @param defaultValue
- * The default value.
- * @return A String value.
- */
- public String optString(int index, String defaultValue) {
- Object object = this.opt(index);
- return JSONObject.NULL.equals(object) ? defaultValue : object
- .toString();
- }
-
- /**
- * Append a boolean value. This increases the array's length by one.
- *
- * @param value
- * A boolean value.
- * @return this.
- */
- public JSONArray put(boolean value) {
- this.put(value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
-
- /**
- * Put a value in the JSONArray, where the value will be a JSONArray which
- * is produced from a Collection.
- *
- * @param value
- * A Collection value.
- * @return this.
- */
- public JSONArray put(Collection value) {
- this.put(new JSONArray(value));
- return this;
- }
-
- /**
- * Append a double value. This increases the array's length by one.
- *
- * @param value
- * A double value.
- * @throws JSONException
- * if the value is not finite.
- * @return this.
- */
- public JSONArray put(double value) throws JSONException {
- Double d = new Double(value);
- JSONObject.testValidity(d);
- this.put(d);
- return this;
- }
-
- /**
- * Append an int value. This increases the array's length by one.
- *
- * @param value
- * An int value.
- * @return this.
- */
- public JSONArray put(int value) {
- this.put(new Integer(value));
- return this;
- }
-
- /**
- * Append an long value. This increases the array's length by one.
- *
- * @param value
- * A long value.
- * @return this.
- */
- public JSONArray put(long value) {
- this.put(new Long(value));
- return this;
- }
-
- /**
- * Put a value in the JSONArray, where the value will be a JSONObject which
- * is produced from a Map.
- *
- * @param value
- * A Map value.
- * @return this.
- */
- public JSONArray put(Map value) {
- this.put(new JSONObject(value));
- return this;
- }
-
- /**
- * Append an object value. This increases the array's length by one.
- *
- * @param value
- * An object value. The value should be a Boolean, Double,
- * Integer, JSONArray, JSONObject, Long, or String, or the
- * JSONObject.NULL object.
- * @return this.
- */
- public JSONArray put(Object value) {
- this.myArrayList.add(value);
- return this;
- }
-
- /**
- * Put or replace a boolean value in the JSONArray. If the index is greater
- * than the length of the JSONArray, then null elements will be added as
- * necessary to pad it out.
- *
- * @param index
- * The subscript.
- * @param value
- * A boolean value.
- * @return this.
- * @throws JSONException
- * If the index is negative.
- */
- public JSONArray put(int index, boolean value) throws JSONException {
- this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
-
- /**
- * Put a value in the JSONArray, where the value will be a JSONArray which
- * is produced from a Collection.
- *
- * @param index
- * The subscript.
- * @param value
- * A Collection value.
- * @return this.
- * @throws JSONException
- * If the index is negative or if the value is not finite.
- */
- public JSONArray put(int index, Collection value) throws JSONException {
- this.put(index, new JSONArray(value));
- return this;
- }
-
- /**
- * Put or replace a double value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad it
- * out.
- *
- * @param index
- * The subscript.
- * @param value
- * A double value.
- * @return this.
- * @throws JSONException
- * If the index is negative or if the value is not finite.
- */
- public JSONArray put(int index, double value) throws JSONException {
- this.put(index, new Double(value));
- return this;
- }
-
- /**
- * Put or replace an int value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad it
- * out.
- *
- * @param index
- * The subscript.
- * @param value
- * An int value.
- * @return this.
- * @throws JSONException
- * If the index is negative.
- */
- public JSONArray put(int index, int value) throws JSONException {
- this.put(index, new Integer(value));
- return this;
- }
-
- /**
- * Put or replace a long value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad it
- * out.
- *
- * @param index
- * The subscript.
- * @param value
- * A long value.
- * @return this.
- * @throws JSONException
- * If the index is negative.
- */
- public JSONArray put(int index, long value) throws JSONException {
- this.put(index, new Long(value));
- return this;
- }
-
- /**
- * Put a value in the JSONArray, where the value will be a JSONObject that
- * is produced from a Map.
- *
- * @param index
- * The subscript.
- * @param value
- * The Map value.
- * @return this.
- * @throws JSONException
- * If the index is negative or if the the value is an invalid
- * number.
- */
- public JSONArray put(int index, Map value) throws JSONException {
- this.put(index, new JSONObject(value));
- return this;
- }
-
- /**
- * Put or replace an object value in the JSONArray. If the index is greater
- * than the length of the JSONArray, then null elements will be added as
- * necessary to pad it out.
- *
- * @param index
- * The subscript.
- * @param value
- * The value to put into the array. The value should be a
- * Boolean, Double, Integer, JSONArray, JSONObject, Long, or
- * String, or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException
- * If the index is negative or if the the value is an invalid
- * number.
- */
- public JSONArray put(int index, Object value) throws JSONException {
- JSONObject.testValidity(value);
- if (index < 0) {
- throw new JSONException("JSONArray[" + index + "] not found.");
- }
- if (index < this.length()) {
- this.myArrayList.set(index, value);
- } else {
- while (index != this.length()) {
- this.put(JSONObject.NULL);
- }
- this.put(value);
- }
- return this;
- }
-
- /**
- * Remove an index and close the hole.
- *
- * @param index
- * The index of the element to be removed.
- * @return The value that was associated with the index, or null if there
- * was no value.
- */
- public Object remove(int index) {
- Object o = this.opt(index);
- this.myArrayList.remove(index);
- return o;
- }
-
- /**
- * Produce a JSONObject by combining a JSONArray of names with the values of
- * this JSONArray.
- *
- * @param names
- * A JSONArray containing a list of key strings. These will be
- * paired with the values.
- * @return A JSONObject, or null if there are no names or if this JSONArray
- * has no values.
- * @throws JSONException
- * If any of the names are null.
- */
- public JSONObject toJSONObject(JSONArray names) throws JSONException {
- if (names == null || names.length() == 0 || this.length() == 0) {
- return null;
- }
- JSONObject jo = new JSONObject();
- for (int i = 0; i < names.length(); i += 1) {
- jo.put(names.getString(i), this.opt(i));
- }
- return jo;
- }
-
- /**
- * Make a JSON text of this JSONArray. For compactness, no unnecessary
- * whitespace is added. If it is not possible to produce a syntactically
- * correct JSON text then null will be returned instead. This could occur if
- * the array contains an invalid number.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return a printable, displayable, transmittable representation of the
- * array.
- */
- public String toString() {
- try {
- return this.toString(0);
- } catch (Exception e) {
- return null;
- }
- }
-
- /**
- * Make a prettyprinted JSON text of this JSONArray. Warning: This method
- * assumes that the data structure is acyclical.
- *
- * @param indentFactor
- * The number of spaces to add to each level of indentation.
- * @return a printable, displayable, transmittable representation of the
- * object, beginning with [ (left
- * bracket) and ending with ]
- * (right bracket).
- * @throws JSONException
- */
- public String toString(int indentFactor) throws JSONException {
- StringWriter sw = new StringWriter();
- synchronized (sw.getBuffer()) {
- return this.write(sw, indentFactor, 0).toString();
- }
- }
-
- /**
- * Write the contents of the JSONArray as JSON text to a writer. For
- * compactness, no whitespace is added.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer) throws JSONException {
- return this.write(writer, 0, 0);
- }
-
- /**
- * Write the contents of the JSONArray as JSON text to a writer. For
- * compactness, no whitespace is added.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @param indentFactor
- * The number of spaces to add to each level of indentation.
- * @param indent
- * The indention of the top level.
- * @return The writer.
- * @throws JSONException
- */
- Writer write(Writer writer, int indentFactor, int indent)
- throws JSONException {
- try {
- boolean commanate = false;
- int length = this.length();
- writer.write('[');
-
- if (length == 1) {
- JSONObject.writeValue(writer, this.myArrayList.get(0),
- indentFactor, indent);
- } else if (length != 0) {
- final int newindent = indent + indentFactor;
-
- for (int i = 0; i < length; i += 1) {
- if (commanate) {
- writer.write(',');
- }
- if (indentFactor > 0) {
- writer.write('\n');
- }
- JSONObject.indent(writer, newindent);
- JSONObject.writeValue(writer, this.myArrayList.get(i),
- indentFactor, newindent);
- commanate = true;
- }
- if (indentFactor > 0) {
- writer.write('\n');
- }
- JSONObject.indent(writer, indent);
- }
- writer.write(']');
- return writer;
- } catch (IOException e) {
- throw new JSONException(e);
- }
- }
-}
diff --git a/JSONException.java b/JSONException.java
deleted file mode 100755
index 971547e63..000000000
--- a/JSONException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package org.json;
-
-/**
- * The JSONException is thrown by the JSON.org classes when things are amiss.
- *
- * @author JSON.org
- * @version 2013-02-10
- */
-public class JSONException extends RuntimeException {
- private static final long serialVersionUID = 0;
- private Throwable cause;
-
- /**
- * Constructs a JSONException with an explanatory message.
- *
- * @param message
- * Detail about the reason for the exception.
- */
- public JSONException(String message) {
- super(message);
- }
-
- /**
- * Constructs a new JSONException with the specified cause.
- */
- public JSONException(Throwable cause) {
- super(cause.getMessage());
- this.cause = cause;
- }
-
- /**
- * Returns the cause of this exception or null if the cause is nonexistent
- * or unknown.
- *
- * @returns the cause of this exception or null if the cause is nonexistent
- * or unknown.
- */
- public Throwable getCause() {
- return this.cause;
- }
-}
diff --git a/JSONObject.java b/JSONObject.java
deleted file mode 100755
index 9d2d5cee3..000000000
--- a/JSONObject.java
+++ /dev/null
@@ -1,1664 +0,0 @@
-package org.json;
-
-/*
- Copyright (c) 2002 JSON.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
-
- The Software shall be used for Good, not Evil.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE.
- */
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Map;
-import java.util.ResourceBundle;
-import java.util.Set;
-
-/**
- * A JSONObject is an unordered collection of name/value pairs. Its external
- * form is a string wrapped in curly braces with colons between the names and
- * values, and commas between the values and names. The internal form is an
- * object having get and opt methods for accessing
- * the values by name, and put methods for adding or replacing
- * values by name. The values can be any of these types: Boolean,
- * JSONArray, JSONObject, Number,
- * String, or the JSONObject.NULL object. A
- * JSONObject constructor can be used to convert an external form JSON text
- * into an internal form whose values can be retrieved with the
- * get and opt methods, or to convert values into a
- * JSON text using the put and toString methods. A
- * get method returns a value if one can be found, and throws an
- * exception if one cannot be found. An opt method returns a
- * default value instead of throwing an exception, and so is useful for
- * obtaining optional values.
- *
- * The generic get() and opt() methods return an
- * object, which you can cast or query for type. There are also typed
- * get and opt methods that do type checking and type
- * coercion for you. The opt methods differ from the get methods in that they
- * do not throw. Instead, they return a specified value, such as null.
- *
- * The put methods add or replace values in an object. For
- * example,
- *
- *
- * The texts produced by the toString methods strictly conform to
- * the JSON syntax rules. The constructors are more forgiving in the texts they
- * will accept:
- *
- *
An extra , (comma) may appear just
- * before the closing brace.
- *
Strings may be quoted with ' (single
- * quote).
- *
Strings do not need to be quoted at all if they do not begin with a
- * quote or single quote, and if they do not contain leading or trailing
- * spaces, and if they do not contain any of these characters:
- * { } [ ] / \ : , # and if they do not look like numbers and
- * if they are not the reserved words true, false,
- * or null.
- *
- *
- * @author JSON.org
- * @version 2013-04-18
- */
-public class JSONObject {
- /**
- * The maximum number of keys in the key pool.
- */
- private static final int keyPoolSize = 100;
-
- /**
- * Key pooling is like string interning, but without permanently tying up
- * memory. To help conserve memory, storage of duplicated key strings in
- * JSONObjects will be avoided by using a key pool to manage unique key
- * string objects. This is used by JSONObject.put(string, object).
- */
- private static HashMap keyPool = new HashMap(keyPoolSize);
-
- /**
- * JSONObject.NULL is equivalent to the value that JavaScript calls null,
- * whilst Java's null is equivalent to the value that JavaScript calls
- * undefined.
- */
- private static final class Null {
-
- /**
- * There is only intended to be a single instance of the NULL object,
- * so the clone method returns itself.
- *
- * @return NULL.
- */
- protected final Object clone() {
- return this;
- }
-
- /**
- * A Null object is equal to the null value and to itself.
- *
- * @param object
- * An object to test for nullness.
- * @return true if the object parameter is the JSONObject.NULL object or
- * null.
- */
- public boolean equals(Object object) {
- return object == null || object == this;
- }
-
- /**
- * Get the "null" string value.
- *
- * @return The string "null".
- */
- public String toString() {
- return "null";
- }
- }
-
- /**
- * The map where the JSONObject's properties are kept.
- */
- private final Map map;
-
- /**
- * It is sometimes more convenient and less ambiguous to have a
- * NULL object than to use Java's null value.
- * JSONObject.NULL.equals(null) returns true.
- * JSONObject.NULL.toString() returns "null".
- */
- public static final Object NULL = new Null();
-
- /**
- * Construct an empty JSONObject.
- */
- public JSONObject() {
- this.map = new HashMap();
- }
-
- /**
- * Construct a JSONObject from a subset of another JSONObject. An array of
- * strings is used to identify the keys that should be copied. Missing keys
- * are ignored.
- *
- * @param jo
- * A JSONObject.
- * @param names
- * An array of strings.
- * @throws JSONException
- * @exception JSONException
- * If a value is a non-finite number or if a name is
- * duplicated.
- */
- public JSONObject(JSONObject jo, String[] names) {
- this();
- for (int i = 0; i < names.length; i += 1) {
- try {
- this.putOnce(names[i], jo.opt(names[i]));
- } catch (Exception ignore) {
- }
- }
- }
-
- /**
- * Construct a JSONObject from a JSONTokener.
- *
- * @param x
- * A JSONTokener object containing the source string.
- * @throws JSONException
- * If there is a syntax error in the source string or a
- * duplicated key.
- */
- public JSONObject(JSONTokener x) throws JSONException {
- this();
- char c;
- String key;
-
- if (x.nextClean() != '{') {
- throw x.syntaxError("A JSONObject text must begin with '{'");
- }
- for (;;) {
- c = x.nextClean();
- switch (c) {
- case 0:
- throw x.syntaxError("A JSONObject text must end with '}'");
- case '}':
- return;
- default:
- x.back();
- key = x.nextValue().toString();
- }
-
-// The key is followed by ':'.
-
- c = x.nextClean();
- if (c != ':') {
- throw x.syntaxError("Expected a ':' after a key");
- }
- this.putOnce(key, x.nextValue());
-
-// Pairs are separated by ','.
-
- switch (x.nextClean()) {
- case ';':
- case ',':
- if (x.nextClean() == '}') {
- return;
- }
- x.back();
- break;
- case '}':
- return;
- default:
- throw x.syntaxError("Expected a ',' or '}'");
- }
- }
- }
-
- /**
- * Construct a JSONObject from a Map.
- *
- * @param map
- * A map object that can be used to initialize the contents of
- * the JSONObject.
- * @throws JSONException
- */
- public JSONObject(Map map) {
- this.map = new HashMap();
- if (map != null) {
- Iterator i = map.entrySet().iterator();
- while (i.hasNext()) {
- Map.Entry e = (Map.Entry) i.next();
- Object value = e.getValue();
- if (value != null) {
- this.map.put(e.getKey(), wrap(value));
- }
- }
- }
- }
-
- /**
- * Construct a JSONObject from an Object using bean getters. It reflects on
- * all of the public methods of the object. For each of the methods with no
- * parameters and a name starting with "get" or
- * "is" followed by an uppercase letter, the method is invoked,
- * and a key and the value returned from the getter method are put into the
- * new JSONObject.
- *
- * The key is formed by removing the "get" or "is"
- * prefix. If the second remaining character is not upper case, then the
- * first character is converted to lower case.
- *
- * For example, if an object has a method named "getName", and
- * if the result of calling object.getName() is
- * "Larry Fine", then the JSONObject will contain
- * "name": "Larry Fine".
- *
- * @param bean
- * An object that has getter methods that should be used to make
- * a JSONObject.
- */
- public JSONObject(Object bean) {
- this();
- this.populateMap(bean);
- }
-
- /**
- * Construct a JSONObject from an Object, using reflection to find the
- * public members. The resulting JSONObject's keys will be the strings from
- * the names array, and the values will be the field values associated with
- * those keys in the object. If a key is not found or not visible, then it
- * will not be copied into the new JSONObject.
- *
- * @param object
- * An object that has fields that should be used to make a
- * JSONObject.
- * @param names
- * An array of strings, the names of the fields to be obtained
- * from the object.
- */
- public JSONObject(Object object, String names[]) {
- this();
- Class c = object.getClass();
- for (int i = 0; i < names.length; i += 1) {
- String name = names[i];
- try {
- this.putOpt(name, c.getField(name).get(object));
- } catch (Exception ignore) {
- }
- }
- }
-
- /**
- * Construct a JSONObject from a source JSON text string. This is the most
- * commonly used JSONObject constructor.
- *
- * @param source
- * A string beginning with { (left
- * brace) and ending with }
- * (right brace).
- * @exception JSONException
- * If there is a syntax error in the source string or a
- * duplicated key.
- */
- public JSONObject(String source) throws JSONException {
- this(new JSONTokener(source));
- }
-
- /**
- * Construct a JSONObject from a ResourceBundle.
- *
- * @param baseName
- * The ResourceBundle base name.
- * @param locale
- * The Locale to load the ResourceBundle for.
- * @throws JSONException
- * If any JSONExceptions are detected.
- */
- public JSONObject(String baseName, Locale locale) throws JSONException {
- this();
- ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
- Thread.currentThread().getContextClassLoader());
-
-// Iterate through the keys in the bundle.
-
- Enumeration keys = bundle.getKeys();
- while (keys.hasMoreElements()) {
- Object key = keys.nextElement();
- if (key instanceof String) {
-
-// Go through the path, ensuring that there is a nested JSONObject for each
-// segment except the last. Add the value using the last segment's name into
-// the deepest nested JSONObject.
-
- String[] path = ((String) key).split("\\.");
- int last = path.length - 1;
- JSONObject target = this;
- for (int i = 0; i < last; i += 1) {
- String segment = path[i];
- JSONObject nextTarget = target.optJSONObject(segment);
- if (nextTarget == null) {
- nextTarget = new JSONObject();
- target.put(segment, nextTarget);
- }
- target = nextTarget;
- }
- target.put(path[last], bundle.getString((String) key));
- }
- }
- }
-
- /**
- * Accumulate values under a key. It is similar to the put method except
- * that if there is already an object stored under the key then a JSONArray
- * is stored under the key to hold all of the accumulated values. If there
- * is already a JSONArray, then the new value is appended to it. In
- * contrast, the put method replaces the previous value.
- *
- * If only one value is accumulated that is not a JSONArray, then the result
- * will be the same as using put. But if multiple values are accumulated,
- * then the result will be like append.
- *
- * @param key
- * A key string.
- * @param value
- * An object to be accumulated under the key.
- * @return this.
- * @throws JSONException
- * If the value is an invalid number or if the key is null.
- */
- public JSONObject accumulate(String key, Object value) throws JSONException {
- testValidity(value);
- Object object = this.opt(key);
- if (object == null) {
- this.put(key,
- value instanceof JSONArray ? new JSONArray().put(value)
- : value);
- } else if (object instanceof JSONArray) {
- ((JSONArray) object).put(value);
- } else {
- this.put(key, new JSONArray().put(object).put(value));
- }
- return this;
- }
-
- /**
- * Append values to the array under a key. If the key does not exist in the
- * JSONObject, then the key is put in the JSONObject with its value being a
- * JSONArray containing the value parameter. If the key was already
- * associated with a JSONArray, then the value parameter is appended to it.
- *
- * @param key
- * A key string.
- * @param value
- * An object to be accumulated under the key.
- * @return this.
- * @throws JSONException
- * If the key is null or if the current value associated with
- * the key is not a JSONArray.
- */
- public JSONObject append(String key, Object value) throws JSONException {
- testValidity(value);
- Object object = this.opt(key);
- if (object == null) {
- this.put(key, new JSONArray().put(value));
- } else if (object instanceof JSONArray) {
- this.put(key, ((JSONArray) object).put(value));
- } else {
- throw new JSONException("JSONObject[" + key
- + "] is not a JSONArray.");
- }
- return this;
- }
-
- /**
- * Produce a string from a double. The string "null" will be returned if the
- * number is not finite.
- *
- * @param d
- * A double.
- * @return A String.
- */
- public static String doubleToString(double d) {
- if (Double.isInfinite(d) || Double.isNaN(d)) {
- return "null";
- }
-
-// Shave off trailing zeros and decimal point, if possible.
-
- String string = Double.toString(d);
- if (string.indexOf('.') > 0 && string.indexOf('e') < 0
- && string.indexOf('E') < 0) {
- while (string.endsWith("0")) {
- string = string.substring(0, string.length() - 1);
- }
- if (string.endsWith(".")) {
- string = string.substring(0, string.length() - 1);
- }
- }
- return string;
- }
-
- /**
- * Get the value object associated with a key.
- *
- * @param key
- * A key string.
- * @return The object associated with the key.
- * @throws JSONException
- * if the key is not found.
- */
- public Object get(String key) throws JSONException {
- if (key == null) {
- throw new JSONException("Null key.");
- }
- Object object = this.opt(key);
- if (object == null) {
- throw new JSONException("JSONObject[" + quote(key) + "] not found.");
- }
- return object;
- }
-
- /**
- * Get the boolean value associated with a key.
- *
- * @param key
- * A key string.
- * @return The truth.
- * @throws JSONException
- * if the value is not a Boolean or the String "true" or
- * "false".
- */
- public boolean getBoolean(String key) throws JSONException {
- Object object = this.get(key);
- if (object.equals(Boolean.FALSE)
- || (object instanceof String && ((String) object)
- .equalsIgnoreCase("false"))) {
- return false;
- } else if (object.equals(Boolean.TRUE)
- || (object instanceof String && ((String) object)
- .equalsIgnoreCase("true"))) {
- return true;
- }
- throw new JSONException("JSONObject[" + quote(key)
- + "] is not a Boolean.");
- }
-
- /**
- * Get the double value associated with a key.
- *
- * @param key
- * A key string.
- * @return The numeric value.
- * @throws JSONException
- * if the key is not found or if the value is not a Number
- * object and cannot be converted to a number.
- */
- public double getDouble(String key) throws JSONException {
- Object object = this.get(key);
- try {
- return object instanceof Number ? ((Number) object).doubleValue()
- : Double.parseDouble((String) object);
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key)
- + "] is not a number.");
- }
- }
-
- /**
- * Get the int value associated with a key.
- *
- * @param key
- * A key string.
- * @return The integer value.
- * @throws JSONException
- * if the key is not found or if the value cannot be converted
- * to an integer.
- */
- public int getInt(String key) throws JSONException {
- Object object = this.get(key);
- try {
- return object instanceof Number ? ((Number) object).intValue()
- : Integer.parseInt((String) object);
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key)
- + "] is not an int.");
- }
- }
-
- /**
- * Get the JSONArray value associated with a key.
- *
- * @param key
- * A key string.
- * @return A JSONArray which is the value.
- * @throws JSONException
- * if the key is not found or if the value is not a JSONArray.
- */
- public JSONArray getJSONArray(String key) throws JSONException {
- Object object = this.get(key);
- if (object instanceof JSONArray) {
- return (JSONArray) object;
- }
- throw new JSONException("JSONObject[" + quote(key)
- + "] is not a JSONArray.");
- }
-
- /**
- * Get the JSONObject value associated with a key.
- *
- * @param key
- * A key string.
- * @return A JSONObject which is the value.
- * @throws JSONException
- * if the key is not found or if the value is not a JSONObject.
- */
- public JSONObject getJSONObject(String key) throws JSONException {
- Object object = this.get(key);
- if (object instanceof JSONObject) {
- return (JSONObject) object;
- }
- throw new JSONException("JSONObject[" + quote(key)
- + "] is not a JSONObject.");
- }
-
- /**
- * Get the long value associated with a key.
- *
- * @param key
- * A key string.
- * @return The long value.
- * @throws JSONException
- * if the key is not found or if the value cannot be converted
- * to a long.
- */
- public long getLong(String key) throws JSONException {
- Object object = this.get(key);
- try {
- return object instanceof Number ? ((Number) object).longValue()
- : Long.parseLong((String) object);
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key)
- + "] is not a long.");
- }
- }
-
- /**
- * Get an array of field names from a JSONObject.
- *
- * @return An array of field names, or null if there are no names.
- */
- public static String[] getNames(JSONObject jo) {
- int length = jo.length();
- if (length == 0) {
- return null;
- }
- Iterator iterator = jo.keys();
- String[] names = new String[length];
- int i = 0;
- while (iterator.hasNext()) {
- names[i] = (String) iterator.next();
- i += 1;
- }
- return names;
- }
-
- /**
- * Get an array of field names from an Object.
- *
- * @return An array of field names, or null if there are no names.
- */
- public static String[] getNames(Object object) {
- if (object == null) {
- return null;
- }
- Class klass = object.getClass();
- Field[] fields = klass.getFields();
- int length = fields.length;
- if (length == 0) {
- return null;
- }
- String[] names = new String[length];
- for (int i = 0; i < length; i += 1) {
- names[i] = fields[i].getName();
- }
- return names;
- }
-
- /**
- * Get the string associated with a key.
- *
- * @param key
- * A key string.
- * @return A string which is the value.
- * @throws JSONException
- * if there is no string value for the key.
- */
- public String getString(String key) throws JSONException {
- Object object = this.get(key);
- if (object instanceof String) {
- return (String) object;
- }
- throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
- }
-
- /**
- * Determine if the JSONObject contains a specific key.
- *
- * @param key
- * A key string.
- * @return true if the key exists in the JSONObject.
- */
- public boolean has(String key) {
- return this.map.containsKey(key);
- }
-
- /**
- * Increment a property of a JSONObject. If there is no such property,
- * create one with a value of 1. If there is such a property, and if it is
- * an Integer, Long, Double, or Float, then add one to it.
- *
- * @param key
- * A key string.
- * @return this.
- * @throws JSONException
- * If there is already a property with this name that is not an
- * Integer, Long, Double, or Float.
- */
- public JSONObject increment(String key) throws JSONException {
- Object value = this.opt(key);
- if (value == null) {
- this.put(key, 1);
- } else if (value instanceof Integer) {
- this.put(key, ((Integer) value).intValue() + 1);
- } else if (value instanceof Long) {
- this.put(key, ((Long) value).longValue() + 1);
- } else if (value instanceof Double) {
- this.put(key, ((Double) value).doubleValue() + 1);
- } else if (value instanceof Float) {
- this.put(key, ((Float) value).floatValue() + 1);
- } else {
- throw new JSONException("Unable to increment [" + quote(key) + "].");
- }
- return this;
- }
-
- /**
- * Determine if the value associated with the key is null or if there is no
- * value.
- *
- * @param key
- * A key string.
- * @return true if there is no value associated with the key or if the value
- * is the JSONObject.NULL object.
- */
- public boolean isNull(String key) {
- return JSONObject.NULL.equals(this.opt(key));
- }
-
- /**
- * Get an enumeration of the keys of the JSONObject.
- *
- * @return An iterator of the keys.
- */
- public Iterator keys() {
- return this.keySet().iterator();
- }
-
- /**
- * Get a set of keys of the JSONObject.
- *
- * @return A keySet.
- */
- public Set keySet() {
- return this.map.keySet();
- }
-
- /**
- * Get the number of keys stored in the JSONObject.
- *
- * @return The number of keys in the JSONObject.
- */
- public int length() {
- return this.map.size();
- }
-
- /**
- * Produce a JSONArray containing the names of the elements of this
- * JSONObject.
- *
- * @return A JSONArray containing the key strings, or null if the JSONObject
- * is empty.
- */
- public JSONArray names() {
- JSONArray ja = new JSONArray();
- Iterator keys = this.keys();
- while (keys.hasNext()) {
- ja.put(keys.next());
- }
- return ja.length() == 0 ? null : ja;
- }
-
- /**
- * Produce a string from a Number.
- *
- * @param number
- * A Number
- * @return A String.
- * @throws JSONException
- * If n is a non-finite number.
- */
- public static String numberToString(Number number) throws JSONException {
- if (number == null) {
- throw new JSONException("Null pointer");
- }
- testValidity(number);
-
-// Shave off trailing zeros and decimal point, if possible.
-
- String string = number.toString();
- if (string.indexOf('.') > 0 && string.indexOf('e') < 0
- && string.indexOf('E') < 0) {
- while (string.endsWith("0")) {
- string = string.substring(0, string.length() - 1);
- }
- if (string.endsWith(".")) {
- string = string.substring(0, string.length() - 1);
- }
- }
- return string;
- }
-
- /**
- * Get an optional value associated with a key.
- *
- * @param key
- * A key string.
- * @return An object which is the value, or null if there is no value.
- */
- public Object opt(String key) {
- return key == null ? null : this.map.get(key);
- }
-
- /**
- * Get an optional boolean associated with a key. It returns false if there
- * is no such key, or if the value is not Boolean.TRUE or the String "true".
- *
- * @param key
- * A key string.
- * @return The truth.
- */
- public boolean optBoolean(String key) {
- return this.optBoolean(key, false);
- }
-
- /**
- * Get an optional boolean associated with a key. It returns the
- * defaultValue if there is no such key, or if it is not a Boolean or the
- * String "true" or "false" (case insensitive).
- *
- * @param key
- * A key string.
- * @param defaultValue
- * The default.
- * @return The truth.
- */
- public boolean optBoolean(String key, boolean defaultValue) {
- try {
- return this.getBoolean(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get an optional double associated with a key, or NaN if there is no such
- * key or if its value is not a number. If the value is a string, an attempt
- * will be made to evaluate it as a number.
- *
- * @param key
- * A string which is the key.
- * @return An object which is the value.
- */
- public double optDouble(String key) {
- return this.optDouble(key, Double.NaN);
- }
-
- /**
- * Get an optional double associated with a key, or the defaultValue if
- * there is no such key or if its value is not a number. If the value is a
- * string, an attempt will be made to evaluate it as a number.
- *
- * @param key
- * A key string.
- * @param defaultValue
- * The default.
- * @return An object which is the value.
- */
- public double optDouble(String key, double defaultValue) {
- try {
- return this.getDouble(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get an optional int value associated with a key, or zero if there is no
- * such key or if the value is not a number. If the value is a string, an
- * attempt will be made to evaluate it as a number.
- *
- * @param key
- * A key string.
- * @return An object which is the value.
- */
- public int optInt(String key) {
- return this.optInt(key, 0);
- }
-
- /**
- * Get an optional int value associated with a key, or the default if there
- * is no such key or if the value is not a number. If the value is a string,
- * an attempt will be made to evaluate it as a number.
- *
- * @param key
- * A key string.
- * @param defaultValue
- * The default.
- * @return An object which is the value.
- */
- public int optInt(String key, int defaultValue) {
- try {
- return this.getInt(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get an optional JSONArray associated with a key. It returns null if there
- * is no such key, or if its value is not a JSONArray.
- *
- * @param key
- * A key string.
- * @return A JSONArray which is the value.
- */
- public JSONArray optJSONArray(String key) {
- Object o = this.opt(key);
- return o instanceof JSONArray ? (JSONArray) o : null;
- }
-
- /**
- * Get an optional JSONObject associated with a key. It returns null if
- * there is no such key, or if its value is not a JSONObject.
- *
- * @param key
- * A key string.
- * @return A JSONObject which is the value.
- */
- public JSONObject optJSONObject(String key) {
- Object object = this.opt(key);
- return object instanceof JSONObject ? (JSONObject) object : null;
- }
-
- /**
- * Get an optional long value associated with a key, or zero if there is no
- * such key or if the value is not a number. If the value is a string, an
- * attempt will be made to evaluate it as a number.
- *
- * @param key
- * A key string.
- * @return An object which is the value.
- */
- public long optLong(String key) {
- return this.optLong(key, 0);
- }
-
- /**
- * Get an optional long value associated with a key, or the default if there
- * is no such key or if the value is not a number. If the value is a string,
- * an attempt will be made to evaluate it as a number.
- *
- * @param key
- * A key string.
- * @param defaultValue
- * The default.
- * @return An object which is the value.
- */
- public long optLong(String key, long defaultValue) {
- try {
- return this.getLong(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
- /**
- * Get an optional string associated with a key. It returns an empty string
- * if there is no such key. If the value is not a string and is not null,
- * then it is converted to a string.
- *
- * @param key
- * A key string.
- * @return A string which is the value.
- */
- public String optString(String key) {
- return this.optString(key, "");
- }
-
- /**
- * Get an optional string associated with a key. It returns the defaultValue
- * if there is no such key.
- *
- * @param key
- * A key string.
- * @param defaultValue
- * The default.
- * @return A string which is the value.
- */
- public String optString(String key, String defaultValue) {
- Object object = this.opt(key);
- return NULL.equals(object) ? defaultValue : object.toString();
- }
-
- private void populateMap(Object bean) {
- Class klass = bean.getClass();
-
-// If klass is a System class then set includeSuperClass to false.
-
- boolean includeSuperClass = klass.getClassLoader() != null;
-
- Method[] methods = includeSuperClass ? klass.getMethods() : klass
- .getDeclaredMethods();
- for (int i = 0; i < methods.length; i += 1) {
- try {
- Method method = methods[i];
- if (Modifier.isPublic(method.getModifiers())) {
- String name = method.getName();
- String key = "";
- if (name.startsWith("get")) {
- if ("getClass".equals(name)
- || "getDeclaringClass".equals(name)) {
- key = "";
- } else {
- key = name.substring(3);
- }
- } else if (name.startsWith("is")) {
- key = name.substring(2);
- }
- if (key.length() > 0
- && Character.isUpperCase(key.charAt(0))
- && method.getParameterTypes().length == 0) {
- if (key.length() == 1) {
- key = key.toLowerCase();
- } else if (!Character.isUpperCase(key.charAt(1))) {
- key = key.substring(0, 1).toLowerCase()
- + key.substring(1);
- }
-
- Object result = method.invoke(bean, (Object[]) null);
- if (result != null) {
- this.map.put(key, wrap(result));
- }
- }
- }
- } catch (Exception ignore) {
- }
- }
- }
-
- /**
- * Put a key/boolean pair in the JSONObject.
- *
- * @param key
- * A key string.
- * @param value
- * A boolean which is the value.
- * @return this.
- * @throws JSONException
- * If the key is null.
- */
- public JSONObject put(String key, boolean value) throws JSONException {
- this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
-
- /**
- * Put a key/value pair in the JSONObject, where the value will be a
- * JSONArray which is produced from a Collection.
- *
- * @param key
- * A key string.
- * @param value
- * A Collection value.
- * @return this.
- * @throws JSONException
- */
- public JSONObject put(String key, Collection value) throws JSONException {
- this.put(key, new JSONArray(value));
- return this;
- }
-
- /**
- * Put a key/double pair in the JSONObject.
- *
- * @param key
- * A key string.
- * @param value
- * A double which is the value.
- * @return this.
- * @throws JSONException
- * If the key is null or if the number is invalid.
- */
- public JSONObject put(String key, double value) throws JSONException {
- this.put(key, new Double(value));
- return this;
- }
-
- /**
- * Put a key/int pair in the JSONObject.
- *
- * @param key
- * A key string.
- * @param value
- * An int which is the value.
- * @return this.
- * @throws JSONException
- * If the key is null.
- */
- public JSONObject put(String key, int value) throws JSONException {
- this.put(key, new Integer(value));
- return this;
- }
-
- /**
- * Put a key/long pair in the JSONObject.
- *
- * @param key
- * A key string.
- * @param value
- * A long which is the value.
- * @return this.
- * @throws JSONException
- * If the key is null.
- */
- public JSONObject put(String key, long value) throws JSONException {
- this.put(key, new Long(value));
- return this;
- }
-
- /**
- * Put a key/value pair in the JSONObject, where the value will be a
- * JSONObject which is produced from a Map.
- *
- * @param key
- * A key string.
- * @param value
- * A Map value.
- * @return this.
- * @throws JSONException
- */
- public JSONObject put(String key, Map value) throws JSONException {
- this.put(key, new JSONObject(value));
- return this;
- }
-
- /**
- * Put a key/value pair in the JSONObject. If the value is null, then the
- * key will be removed from the JSONObject if it is present.
- *
- * @param key
- * A key string.
- * @param value
- * An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long,
- * String, or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException
- * If the value is non-finite number or if the key is null.
- */
- public JSONObject put(String key, Object value) throws JSONException {
- String pooled;
- if (key == null) {
- throw new NullPointerException("Null key.");
- }
- if (value != null) {
- testValidity(value);
- pooled = (String) keyPool.get(key);
- if (pooled == null) {
- if (keyPool.size() >= keyPoolSize) {
- keyPool = new HashMap(keyPoolSize);
- }
- keyPool.put(key, key);
- } else {
- key = pooled;
- }
- this.map.put(key, value);
- } else {
- this.remove(key);
- }
- return this;
- }
-
- /**
- * Put a key/value pair in the JSONObject, but only if the key and the value
- * are both non-null, and only if there is not already a member with that
- * name.
- *
- * @param key
- * @param value
- * @return his.
- * @throws JSONException
- * if the key is a duplicate
- */
- public JSONObject putOnce(String key, Object value) throws JSONException {
- if (key != null && value != null) {
- if (this.opt(key) != null) {
- throw new JSONException("Duplicate key \"" + key + "\"");
- }
- this.put(key, value);
- }
- return this;
- }
-
- /**
- * Put a key/value pair in the JSONObject, but only if the key and the value
- * are both non-null.
- *
- * @param key
- * A key string.
- * @param value
- * An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long,
- * String, or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException
- * If the value is a non-finite number.
- */
- public JSONObject putOpt(String key, Object value) throws JSONException {
- if (key != null && value != null) {
- this.put(key, value);
- }
- return this;
- }
-
- /**
- * Produce a string in double quotes with backslash sequences in all the
- * right places. A backslash will be inserted within , producing <\/,
- * allowing JSON text to be delivered in HTML. In JSON text, a string cannot
- * contain a control character or an unescaped quote or backslash.
- *
- * @param string
- * A String
- * @return A String correctly formatted for insertion in a JSON text.
- */
- public static String quote(String string) {
- StringWriter sw = new StringWriter();
- synchronized (sw.getBuffer()) {
- try {
- return quote(string, sw).toString();
- } catch (IOException ignored) {
- // will never happen - we are writing to a string writer
- return "";
- }
- }
- }
-
- public static Writer quote(String string, Writer w) throws IOException {
- if (string == null || string.length() == 0) {
- w.write("\"\"");
- return w;
- }
-
- char b;
- char c = 0;
- String hhhh;
- int i;
- int len = string.length();
-
- w.write('"');
- for (i = 0; i < len; i += 1) {
- b = c;
- c = string.charAt(i);
- switch (c) {
- case '\\':
- case '"':
- w.write('\\');
- w.write(c);
- break;
- case '/':
- if (b == '<') {
- w.write('\\');
- }
- w.write(c);
- break;
- case '\b':
- w.write("\\b");
- break;
- case '\t':
- w.write("\\t");
- break;
- case '\n':
- w.write("\\n");
- break;
- case '\f':
- w.write("\\f");
- break;
- case '\r':
- w.write("\\r");
- break;
- default:
- if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
- || (c >= '\u2000' && c < '\u2100')) {
- w.write("\\u");
- hhhh = Integer.toHexString(c);
- w.write("0000", 0, 4 - hhhh.length());
- w.write(hhhh);
- } else {
- w.write(c);
- }
- }
- }
- w.write('"');
- return w;
- }
-
- /**
- * Remove a name and its value, if present.
- *
- * @param key
- * The name to be removed.
- * @return The value that was associated with the name, or null if there was
- * no value.
- */
- public Object remove(String key) {
- return this.map.remove(key);
- }
-
- /**
- * Try to convert a string into a number, boolean, or null. If the string
- * can't be converted, return the string.
- *
- * @param string
- * A String.
- * @return A simple JSON value.
- */
- public static Object stringToValue(String string) {
- Double d;
- if (string.equals("")) {
- return string;
- }
- if (string.equalsIgnoreCase("true")) {
- return Boolean.TRUE;
- }
- if (string.equalsIgnoreCase("false")) {
- return Boolean.FALSE;
- }
- if (string.equalsIgnoreCase("null")) {
- return JSONObject.NULL;
- }
-
- /*
- * If it might be a number, try converting it. If a number cannot be
- * produced, then the value will just be a string.
- */
-
- char b = string.charAt(0);
- if ((b >= '0' && b <= '9') || b == '-') {
- try {
- if (string.indexOf('.') > -1 || string.indexOf('e') > -1
- || string.indexOf('E') > -1) {
- d = Double.valueOf(string);
- if (!d.isInfinite() && !d.isNaN()) {
- return d;
- }
- } else {
- Long myLong = new Long(string);
- if (string.equals(myLong.toString())) {
- if (myLong.longValue() == myLong.intValue()) {
- return new Integer(myLong.intValue());
- } else {
- return myLong;
- }
- }
- }
- } catch (Exception ignore) {
- }
- }
- return string;
- }
-
- /**
- * Throw an exception if the object is a NaN or infinite number.
- *
- * @param o
- * The object to test.
- * @throws JSONException
- * If o is a non-finite number.
- */
- public static void testValidity(Object o) throws JSONException {
- if (o != null) {
- if (o instanceof Double) {
- if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers.");
- }
- } else if (o instanceof Float) {
- if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers.");
- }
- }
- }
- }
-
- /**
- * Produce a JSONArray containing the values of the members of this
- * JSONObject.
- *
- * @param names
- * A JSONArray containing a list of key strings. This determines
- * the sequence of the values in the result.
- * @return A JSONArray of values.
- * @throws JSONException
- * If any of the values are non-finite numbers.
- */
- public JSONArray toJSONArray(JSONArray names) throws JSONException {
- if (names == null || names.length() == 0) {
- return null;
- }
- JSONArray ja = new JSONArray();
- for (int i = 0; i < names.length(); i += 1) {
- ja.put(this.opt(names.getString(i)));
- }
- return ja;
- }
-
- /**
- * Make a JSON text of this JSONObject. For compactness, no whitespace is
- * added. If this would not result in a syntactically correct JSON text,
- * then null will be returned instead.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return a printable, displayable, portable, transmittable representation
- * of the object, beginning with { (left
- * brace) and ending with } (right
- * brace).
- */
- public String toString() {
- try {
- return this.toString(0);
- } catch (Exception e) {
- return null;
- }
- }
-
- /**
- * Make a prettyprinted JSON text of this JSONObject.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @param indentFactor
- * The number of spaces to add to each level of indentation.
- * @return a printable, displayable, portable, transmittable representation
- * of the object, beginning with { (left
- * brace) and ending with } (right
- * brace).
- * @throws JSONException
- * If the object contains an invalid number.
- */
- public String toString(int indentFactor) throws JSONException {
- StringWriter w = new StringWriter();
- synchronized (w.getBuffer()) {
- return this.write(w, indentFactor, 0).toString();
- }
- }
-
- /**
- * Make a JSON text of an Object value. If the object has an
- * value.toJSONString() method, then that method will be used to produce the
- * JSON text. The method is required to produce a strictly conforming text.
- * If the object does not contain a toJSONString method (which is the most
- * common case), then a text will be produced by other means. If the value
- * is an array or Collection, then a JSONArray will be made from it and its
- * toJSONString method will be called. If the value is a MAP, then a
- * JSONObject will be made from it and its toJSONString method will be
- * called. Otherwise, the value's toString method will be called, and the
- * result will be quoted.
- *
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @param value
- * The value to be serialized.
- * @return a printable, displayable, transmittable representation of the
- * object, beginning with { (left
- * brace) and ending with } (right
- * brace).
- * @throws JSONException
- * If the value is or contains an invalid number.
- */
- public static String valueToString(Object value) throws JSONException {
- if (value == null || value.equals(null)) {
- return "null";
- }
- if (value instanceof JSONString) {
- Object object;
- try {
- object = ((JSONString) value).toJSONString();
- } catch (Exception e) {
- throw new JSONException(e);
- }
- if (object instanceof String) {
- return (String) object;
- }
- throw new JSONException("Bad value from toJSONString: " + object);
- }
- if (value instanceof Number) {
- return numberToString((Number) value);
- }
- if (value instanceof Boolean || value instanceof JSONObject
- || value instanceof JSONArray) {
- return value.toString();
- }
- if (value instanceof Map) {
- return new JSONObject((Map) value).toString();
- }
- if (value instanceof Collection) {
- return new JSONArray((Collection) value).toString();
- }
- if (value.getClass().isArray()) {
- return new JSONArray(value).toString();
- }
- return quote(value.toString());
- }
-
- /**
- * Wrap an object, if necessary. If the object is null, return the NULL
- * object. If it is an array or collection, wrap it in a JSONArray. If it is
- * a map, wrap it in a JSONObject. If it is a standard property (Double,
- * String, et al) then it is already wrapped. Otherwise, if it comes from
- * one of the java packages, turn it into a string. And if it doesn't, try
- * to wrap it in a JSONObject. If the wrapping fails, then null is returned.
- *
- * @param object
- * The object to wrap
- * @return The wrapped value
- */
- public static Object wrap(Object object) {
- try {
- if (object == null) {
- return NULL;
- }
- if (object instanceof JSONObject || object instanceof JSONArray
- || NULL.equals(object) || object instanceof JSONString
- || object instanceof Byte || object instanceof Character
- || object instanceof Short || object instanceof Integer
- || object instanceof Long || object instanceof Boolean
- || object instanceof Float || object instanceof Double
- || object instanceof String) {
- return object;
- }
-
- if (object instanceof Collection) {
- return new JSONArray((Collection) object);
- }
- if (object.getClass().isArray()) {
- return new JSONArray(object);
- }
- if (object instanceof Map) {
- return new JSONObject((Map) object);
- }
- Package objectPackage = object.getClass().getPackage();
- String objectPackageName = objectPackage != null ? objectPackage
- .getName() : "";
- if (objectPackageName.startsWith("java.")
- || objectPackageName.startsWith("javax.")
- || object.getClass().getClassLoader() == null) {
- return object.toString();
- }
- return new JSONObject(object);
- } catch (Exception exception) {
- return null;
- }
- }
-
- /**
- * Write the contents of the JSONObject as JSON text to a writer. For
- * compactness, no whitespace is added.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer) throws JSONException {
- return this.write(writer, 0, 0);
- }
-
- static final Writer writeValue(Writer writer, Object value,
- int indentFactor, int indent) throws JSONException, IOException {
- if (value == null || value.equals(null)) {
- writer.write("null");
- } else if (value instanceof JSONObject) {
- ((JSONObject) value).write(writer, indentFactor, indent);
- } else if (value instanceof JSONArray) {
- ((JSONArray) value).write(writer, indentFactor, indent);
- } else if (value instanceof Map) {
- new JSONObject((Map) value).write(writer, indentFactor, indent);
- } else if (value instanceof Collection) {
- new JSONArray((Collection) value).write(writer, indentFactor,
- indent);
- } else if (value.getClass().isArray()) {
- new JSONArray(value).write(writer, indentFactor, indent);
- } else if (value instanceof Number) {
- writer.write(numberToString((Number) value));
- } else if (value instanceof Boolean) {
- writer.write(value.toString());
- } else if (value instanceof JSONString) {
- Object o;
- try {
- o = ((JSONString) value).toJSONString();
- } catch (Exception e) {
- throw new JSONException(e);
- }
- writer.write(o != null ? o.toString() : quote(value.toString()));
- } else {
- quote(value.toString(), writer);
- }
- return writer;
- }
-
- static final void indent(Writer writer, int indent) throws IOException {
- for (int i = 0; i < indent; i += 1) {
- writer.write(' ');
- }
- }
-
- /**
- * Write the contents of the JSONObject as JSON text to a writer. For
- * compactness, no whitespace is added.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return The writer.
- * @throws JSONException
- */
- Writer write(Writer writer, int indentFactor, int indent)
- throws JSONException {
- try {
- boolean commanate = false;
- final int length = this.length();
- Iterator keys = this.keys();
- writer.write('{');
-
- if (length == 1) {
- Object key = keys.next();
- writer.write(quote(key.toString()));
- writer.write(':');
- if (indentFactor > 0) {
- writer.write(' ');
- }
- writeValue(writer, this.map.get(key), indentFactor, indent);
- } else if (length != 0) {
- final int newindent = indent + indentFactor;
- while (keys.hasNext()) {
- Object key = keys.next();
- if (commanate) {
- writer.write(',');
- }
- if (indentFactor > 0) {
- writer.write('\n');
- }
- indent(writer, newindent);
- writer.write(quote(key.toString()));
- writer.write(':');
- if (indentFactor > 0) {
- writer.write(' ');
- }
- writeValue(writer, this.map.get(key), indentFactor,
- newindent);
- commanate = true;
- }
- if (indentFactor > 0) {
- writer.write('\n');
- }
- indent(writer, indent);
- }
- writer.write('}');
- return writer;
- } catch (IOException exception) {
- throw new JSONException(exception);
- }
- }
-}
diff --git a/JSONTokener.java b/JSONTokener.java
deleted file mode 100644
index 13c84f1f5..000000000
--- a/JSONTokener.java
+++ /dev/null
@@ -1,446 +0,0 @@
-package org.json;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.StringReader;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * A JSONTokener takes a source string and extracts characters and tokens from
- * it. It is used by the JSONObject and JSONArray constructors to parse
- * JSON source strings.
- * @author JSON.org
- * @version 2012-02-16
- */
-public class JSONTokener {
-
- private long character;
- private boolean eof;
- private long index;
- private long line;
- private char previous;
- private Reader reader;
- private boolean usePrevious;
-
-
- /**
- * Construct a JSONTokener from a Reader.
- *
- * @param reader A reader.
- */
- public JSONTokener(Reader reader) {
- this.reader = reader.markSupported()
- ? reader
- : new BufferedReader(reader);
- this.eof = false;
- this.usePrevious = false;
- this.previous = 0;
- this.index = 0;
- this.character = 1;
- this.line = 1;
- }
-
-
- /**
- * Construct a JSONTokener from an InputStream.
- */
- public JSONTokener(InputStream inputStream) throws JSONException {
- this(new InputStreamReader(inputStream));
- }
-
-
- /**
- * Construct a JSONTokener from a string.
- *
- * @param s A source string.
- */
- public JSONTokener(String s) {
- this(new StringReader(s));
- }
-
-
- /**
- * Back up one character. This provides a sort of lookahead capability,
- * so that you can test for a digit or letter before attempting to parse
- * the next number or identifier.
- */
- public void back() throws JSONException {
- if (this.usePrevious || this.index <= 0) {
- throw new JSONException("Stepping back two steps is not supported");
- }
- this.index -= 1;
- this.character -= 1;
- this.usePrevious = true;
- this.eof = false;
- }
-
-
- /**
- * Get the hex value of a character (base16).
- * @param c A character between '0' and '9' or between 'A' and 'F' or
- * between 'a' and 'f'.
- * @return An int between 0 and 15, or -1 if c was not a hex digit.
- */
- public static int dehexchar(char c) {
- if (c >= '0' && c <= '9') {
- return c - '0';
- }
- if (c >= 'A' && c <= 'F') {
- return c - ('A' - 10);
- }
- if (c >= 'a' && c <= 'f') {
- return c - ('a' - 10);
- }
- return -1;
- }
-
- public boolean end() {
- return this.eof && !this.usePrevious;
- }
-
-
- /**
- * Determine if the source string still contains characters that next()
- * can consume.
- * @return true if not yet at the end of the source.
- */
- public boolean more() throws JSONException {
- this.next();
- if (this.end()) {
- return false;
- }
- this.back();
- return true;
- }
-
-
- /**
- * Get the next character in the source string.
- *
- * @return The next character, or 0 if past the end of the source string.
- */
- public char next() throws JSONException {
- int c;
- if (this.usePrevious) {
- this.usePrevious = false;
- c = this.previous;
- } else {
- try {
- c = this.reader.read();
- } catch (IOException exception) {
- throw new JSONException(exception);
- }
-
- if (c <= 0) { // End of stream
- this.eof = true;
- c = 0;
- }
- }
- this.index += 1;
- if (this.previous == '\r') {
- this.line += 1;
- this.character = c == '\n' ? 0 : 1;
- } else if (c == '\n') {
- this.line += 1;
- this.character = 0;
- } else {
- this.character += 1;
- }
- this.previous = (char) c;
- return this.previous;
- }
-
-
- /**
- * Consume the next character, and check that it matches a specified
- * character.
- * @param c The character to match.
- * @return The character.
- * @throws JSONException if the character does not match.
- */
- public char next(char c) throws JSONException {
- char n = this.next();
- if (n != c) {
- throw this.syntaxError("Expected '" + c + "' and instead saw '" +
- n + "'");
- }
- return n;
- }
-
-
- /**
- * Get the next n characters.
- *
- * @param n The number of characters to take.
- * @return A string of n characters.
- * @throws JSONException
- * Substring bounds error if there are not
- * n characters remaining in the source string.
- */
- public String next(int n) throws JSONException {
- if (n == 0) {
- return "";
- }
-
- char[] chars = new char[n];
- int pos = 0;
-
- while (pos < n) {
- chars[pos] = this.next();
- if (this.end()) {
- throw this.syntaxError("Substring bounds error");
- }
- pos += 1;
- }
- return new String(chars);
- }
-
-
- /**
- * Get the next char in the string, skipping whitespace.
- * @throws JSONException
- * @return A character, or 0 if there are no more characters.
- */
- public char nextClean() throws JSONException {
- for (;;) {
- char c = this.next();
- if (c == 0 || c > ' ') {
- return c;
- }
- }
- }
-
-
- /**
- * Return the characters up to the next close quote character.
- * Backslash processing is done. The formal JSON format does not
- * allow strings in single quotes, but an implementation is allowed to
- * accept them.
- * @param quote The quoting character, either
- * " (double quote) or
- * ' (single quote).
- * @return A String.
- * @throws JSONException Unterminated string.
- */
- public String nextString(char quote) throws JSONException {
- char c;
- StringBuffer sb = new StringBuffer();
- for (;;) {
- c = this.next();
- switch (c) {
- case 0:
- case '\n':
- case '\r':
- throw this.syntaxError("Unterminated string");
- case '\\':
- c = this.next();
- switch (c) {
- case 'b':
- sb.append('\b');
- break;
- case 't':
- sb.append('\t');
- break;
- case 'n':
- sb.append('\n');
- break;
- case 'f':
- sb.append('\f');
- break;
- case 'r':
- sb.append('\r');
- break;
- case 'u':
- sb.append((char)Integer.parseInt(this.next(4), 16));
- break;
- case '"':
- case '\'':
- case '\\':
- case '/':
- sb.append(c);
- break;
- default:
- throw this.syntaxError("Illegal escape.");
- }
- break;
- default:
- if (c == quote) {
- return sb.toString();
- }
- sb.append(c);
- }
- }
- }
-
-
- /**
- * Get the text up but not including the specified character or the
- * end of line, whichever comes first.
- * @param delimiter A delimiter character.
- * @return A string.
- */
- public String nextTo(char delimiter) throws JSONException {
- StringBuffer sb = new StringBuffer();
- for (;;) {
- char c = this.next();
- if (c == delimiter || c == 0 || c == '\n' || c == '\r') {
- if (c != 0) {
- this.back();
- }
- return sb.toString().trim();
- }
- sb.append(c);
- }
- }
-
-
- /**
- * Get the text up but not including one of the specified delimiter
- * characters or the end of line, whichever comes first.
- * @param delimiters A set of delimiter characters.
- * @return A string, trimmed.
- */
- public String nextTo(String delimiters) throws JSONException {
- char c;
- StringBuffer sb = new StringBuffer();
- for (;;) {
- c = this.next();
- if (delimiters.indexOf(c) >= 0 || c == 0 ||
- c == '\n' || c == '\r') {
- if (c != 0) {
- this.back();
- }
- return sb.toString().trim();
- }
- sb.append(c);
- }
- }
-
-
- /**
- * Get the next value. The value can be a Boolean, Double, Integer,
- * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
- * @throws JSONException If syntax error.
- *
- * @return An object.
- */
- public Object nextValue() throws JSONException {
- char c = this.nextClean();
- String string;
-
- switch (c) {
- case '"':
- case '\'':
- return this.nextString(c);
- case '{':
- this.back();
- return new JSONObject(this);
- case '[':
- this.back();
- return new JSONArray(this);
- }
-
- /*
- * Handle unquoted text. This could be the values true, false, or
- * null, or it can be a number. An implementation (such as this one)
- * is allowed to also accept non-standard forms.
- *
- * Accumulate characters until we reach the end of the text or a
- * formatting character.
- */
-
- StringBuffer sb = new StringBuffer();
- while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
- sb.append(c);
- c = this.next();
- }
- this.back();
-
- string = sb.toString().trim();
- if ("".equals(string)) {
- throw this.syntaxError("Missing value");
- }
- return JSONObject.stringToValue(string);
- }
-
-
- /**
- * Skip characters until the next character is the requested character.
- * If the requested character is not found, no characters are skipped.
- * @param to A character to skip to.
- * @return The requested character, or zero if the requested character
- * is not found.
- */
- public char skipTo(char to) throws JSONException {
- char c;
- try {
- long startIndex = this.index;
- long startCharacter = this.character;
- long startLine = this.line;
- this.reader.mark(1000000);
- do {
- c = this.next();
- if (c == 0) {
- this.reader.reset();
- this.index = startIndex;
- this.character = startCharacter;
- this.line = startLine;
- return c;
- }
- } while (c != to);
- } catch (IOException exc) {
- throw new JSONException(exc);
- }
-
- this.back();
- return c;
- }
-
-
- /**
- * Make a JSONException to signal a syntax error.
- *
- * @param message The error message.
- * @return A JSONException object, suitable for throwing
- */
- public JSONException syntaxError(String message) {
- return new JSONException(message + this.toString());
- }
-
-
- /**
- * Make a printable string of this JSONTokener.
- *
- * @return " at {index} [character {character} line {line}]"
- */
- public String toString() {
- return " at " + this.index + " [character " + this.character + " line " +
- this.line + "]";
- }
-}
diff --git a/Kim.java b/Kim.java
deleted file mode 100644
index d4770b566..000000000
--- a/Kim.java
+++ /dev/null
@@ -1,373 +0,0 @@
-package org.json;
-
-
-/*
- Copyright (c) 2013 JSON.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
-
- The Software shall be used for Good, not Evil.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE.
- */
-
-/**
- * Kim makes immutable eight bit Unicode strings. If the MSB of a byte is set,
- * then the next byte is a continuation byte. The last byte of a character
- * never has the MSB reset. Every byte that is not the last byte has the MSB
- * set. Kim stands for "Keep it minimal". A Unicode character is never longer
- * than 3 bytes. Every byte contributes 7 bits to the character. ASCII is
- * unmodified.
- *
- * Kim UTF-8
- * one byte U+007F U+007F
- * two bytes U+3FFF U+07FF
- * three bytes U+10FFF U+FFFF
- * four bytes U+10FFFF
- *
- * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one
- * byte smaller when encoded in Kim compared to UTF-8.
- *
- * Kim is beneficial when using scripts such as Old South Arabian, Aramaic,
- * Avestan, Balinese, Batak, Bopomofo, Buginese, Buhid, Carian, Cherokee,
- * Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian,
- * Glagolitic, Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi,
- * Kannada, Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu, Lycian, Lydian,
- * Malayalam, Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue,
- * Ol Chiki, Old Turkic, Oriya, Osmanya, Pahlavi, Parthian, Phags-Pa,
- * Phoenician, Samaritan, Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa,
- * Takri, Tai Le, Tai Tham, Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS.
- *
- * A kim object can be constructed from an ordinary UTF-16 string, or from a
- * byte array. A kim object can produce a UTF-16 string.
- *
- * As with UTF-8, it is possible to detect character boundaries within a byte
- * sequence. UTF-8 is one of the world's great inventions. While Kim is more
- * efficient, it is not clear that it is worth the expense of transition.
- *
- * @version 2013-04-18
- */
-public class Kim {
-
- /**
- * The byte array containing the kim's content.
- */
- private byte[] bytes = null;
-
- /**
- * The kim's hashcode, conforming to Java's hashcode conventions.
- */
- private int hashcode = 0;
-
- /**
- * The number of bytes in the kim. The number of bytes can be as much as
- * three times the number of characters.
- */
- public int length = 0;
-
- /**
- * The memoization of toString().
- */
- private String string = null;
-
- /**
- * Make a kim from a portion of a byte array.
- *
- * @param bytes
- * A byte array.
- * @param from
- * The index of the first byte.
- * @param thru
- * The index of the last byte plus one.
- */
- public Kim(byte[] bytes, int from, int thru) {
-
-// As the bytes are copied into the new kim, a hashcode is computed using a
-// modified Fletcher code.
-
- int sum = 1;
- int value;
- this.hashcode = 0;
- this.length = thru - from;
- if (this.length > 0) {
- this.bytes = new byte[this.length];
- for (int at = 0; at < this.length; at += 1) {
- value = (int) bytes[at + from] & 0xFF;
- sum += value;
- this.hashcode += sum;
- this.bytes[at] = (byte) value;
- }
- this.hashcode += sum << 16;
- }
- }
-
- /**
- * Make a kim from a byte array.
- *
- * @param bytes
- * The byte array.
- * @param length
- * The number of bytes.
- */
- public Kim(byte[] bytes, int length) {
- this(bytes, 0, length);
- }
-
- /**
- * Make a new kim from a substring of an existing kim. The coordinates are
- * in byte units, not character units.
- *
- * @param kim
- * The source of bytes.
- * @param from
- * The point at which to take bytes.
- * @param thru
- * The point at which to stop taking bytes.
- * @return the substring
- */
- public Kim(Kim kim, int from, int thru) {
- this(kim.bytes, from, thru);
- }
-
- /**
- * Make a kim from a string.
- *
- * @param string
- * The string.
- * @throws JSONException
- * if surrogate pair mismatch.
- */
- public Kim(String string) throws JSONException {
- int stringLength = string.length();
- this.hashcode = 0;
- this.length = 0;
-
-// First pass: Determine the length of the kim, allowing for the UTF-16
-// to UTF-32 conversion, and then the UTF-32 to Kim conversion.
-
- if (stringLength > 0) {
- for (int i = 0; i < stringLength; i += 1) {
- int c = string.charAt(i);
- if (c <= 0x7F) {
- this.length += 1;
- } else if (c <= 0x3FFF) {
- this.length += 2;
- } else {
- if (c >= 0xD800 && c <= 0xDFFF) {
- i += 1;
- int d = string.charAt(i);
- if (c > 0xDBFF || d < 0xDC00 || d > 0xDFFF) {
- throw new JSONException("Bad UTF16");
- }
- }
- this.length += 3;
- }
- }
-
-// Second pass: Allocate a byte array and fill that array with the conversion
-// while computing the hashcode.
-
- this.bytes = new byte[length];
- int at = 0;
- int b;
- int sum = 1;
- for (int i = 0; i < stringLength; i += 1) {
- int character = string.charAt(i);
- if (character <= 0x7F) {
- bytes[at] = (byte) character;
- sum += character;
- this.hashcode += sum;
- at += 1;
- } else if (character <= 0x3FFF) {
- b = 0x80 | (character >>> 7);
- bytes[at] = (byte) b;
- sum += b;
- this.hashcode += sum;
- at += 1;
- b = character & 0x7F;
- bytes[at] = (byte) b;
- sum += b;
- this.hashcode += sum;
- at += 1;
- } else {
- if (character >= 0xD800 && character <= 0xDBFF) {
- i += 1;
- character = (((character & 0x3FF) << 10) | (string
- .charAt(i) & 0x3FF)) + 65536;
- }
- b = 0x80 | (character >>> 14);
- bytes[at] = (byte) b;
- sum += b;
- this.hashcode += sum;
- at += 1;
- b = 0x80 | ((character >>> 7) & 0xFF);
- bytes[at] = (byte) b;
- sum += b;
- this.hashcode += sum;
- at += 1;
- b = character & 0x7F;
- bytes[at] = (byte) b;
- sum += b;
- this.hashcode += sum;
- at += 1;
- }
- }
- this.hashcode += sum << 16;
- }
- }
-
- /**
- * Returns the character at the specified index. The index refers to byte
- * values and ranges from 0 to length - 1. The index of the next character
- * is at index + Kim.characterSize(kim.characterAt(index)).
- *
- * @param at
- * the index of the char value. The first character is at 0.
- * @returns a Unicode character between 0 and 0x10FFFF.
- * @throws JSONException
- * if at does not point to a valid character.
- */
- public int characterAt(int at) throws JSONException {
- int c = get(at);
- if ((c & 0x80) == 0) {
- return c;
- }
- int character;
- int c1 = get(at + 1);
- if ((c1 & 0x80) == 0) {
- character = ((c & 0x7F) << 7) | c1;
- if (character > 0x7F) {
- return character;
- }
- } else {
- int c2 = get(at + 2);
- character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
- if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF
- && (character < 0xD800 || character > 0xDFFF)) {
- return character;
- }
- }
- throw new JSONException("Bad character at " + at);
- }
-
- /**
- * Returns the number of bytes needed to contain the character in Kim
- * format.
- *
- * @param character
- * a Unicode character between 0 and 0x10FFFF.
- * @return 1, 2, or 3
- * @throws JSONException
- * if the character is not representable in a kim.
- */
- public static int characterSize(int character) throws JSONException {
- if (character < 0 || character > 0x10FFFF) {
- throw new JSONException("Bad character " + character);
- }
- return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3;
- }
-
- /**
- * Copy the contents of this kim to a byte array.
- *
- * @param bytes
- * A byte array of sufficient size.
- * @param at
- * The position within the byte array to take the byes.
- * @return The position immediately after the copy.
- */
- public int copy(byte[] bytes, int at) {
- System.arraycopy(this.bytes, 0, bytes, at, this.length);
- return at + this.length;
- }
-
- /**
- * Two kim objects containing exactly the same bytes in the same order are
- * equal to each other.
- *
- * @param obj
- * the other kim with which to compare.
- * @returns true if this and obj are both kim objects containing identical
- * byte sequences.
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof Kim)) {
- return false;
- }
- Kim that = (Kim) obj;
- if (this == that) {
- return true;
- }
- if (this.hashcode != that.hashcode) {
- return false;
- }
- return java.util.Arrays.equals(this.bytes, that.bytes);
- }
-
- /**
- * Get a byte from a kim.
- * @param at
- * The position of the byte. The first byte is at 0.
- * @return The byte.
- * @throws JSONException
- * if there is no byte at that position.
- */
- public int get(int at) throws JSONException {
- if (at < 0 || at > this.length) {
- throw new JSONException("Bad character at " + at);
- }
- return ((int) this.bytes[at]) & 0xFF;
- }
-
- /**
- * Returns a hash code value for the kim.
- */
- public int hashCode() {
- return this.hashcode;
- }
-
- /**
- * Produce a UTF-16 String from this kim. The number of codepoints in the
- * string will not be greater than the number of bytes in the kim, although
- * it could be less.
- *
- * @return The string. A kim memoizes its string representation.
- * @throws JSONException
- * if the kim is not valid.
- */
- public String toString() throws JSONException {
- if (this.string == null) {
- int c;
- int length = 0;
- char chars[] = new char[this.length];
- for (int at = 0; at < this.length; at += characterSize(c)) {
- c = this.characterAt(at);
- if (c < 0x10000) {
- chars[length] = (char) c;
- length += 1;
- } else {
- chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10));
- length += 1;
- chars[length] = (char) (0xDC00 | (c & 0x03FF));
- length += 1;
- }
- }
- this.string = new String(chars, 0, length);
- }
- return this.string;
- }
-}
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..2ef9799e0
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,2 @@
+Public Domain.
+
diff --git a/README b/README
deleted file mode 100755
index b77c71a21..000000000
--- a/README
+++ /dev/null
@@ -1,68 +0,0 @@
-JSON in Java [package org.json]
-
-Douglas Crockford
-douglas@crockford.com
-
-2011-02-02
-
-
-JSON is a light-weight, language independent, data interchange format.
-See http://www.JSON.org/
-
-The files in this package implement JSON encoders/decoders in Java.
-It also includes the capability to convert between JSON and XML, HTTP
-headers, Cookies, and CDL.
-
-This is a reference implementation. There is a large number of JSON packages
-in Java. Perhaps someday the Java community will standardize on one. Until
-then, choose carefully.
-
-The license includes this restriction: "The software shall be used for good,
-not evil." If your conscience cannot live with that, then choose a different
-package.
-
-The package compiles on Java 1.2 thru Java 1.4.
-
-
-JSONObject.java: The JSONObject can parse text from a String or a JSONTokener
-to produce a map-like object. The object provides methods for manipulating its
-contents, and for producing a JSON compliant object serialization.
-
-JSONArray.java: The JSONObject can parse text from a String or a JSONTokener
-to produce a vector-like object. The object provides methods for manipulating
-its contents, and for producing a JSON compliant array serialization.
-
-JSONTokener.java: The JSONTokener breaks a text into a sequence of individual
-tokens. It can be constructed from a String, Reader, or InputStream.
-
-JSONException.java: The JSONException is the standard exception type thrown
-by this package.
-
-
-JSONString.java: The JSONString interface requires a toJSONString method,
-allowing an object to provide its own serialization.
-
-JSONStringer.java: The JSONStringer provides a convenient facility for
-building JSON strings.
-
-JSONWriter.java: The JSONWriter provides a convenient facility for building
-JSON text through a writer.
-
-
-CDL.java: CDL provides support for converting between JSON and comma
-delimited lists.
-
-Cookie.java: Cookie provides support for converting between JSON and cookies.
-
-CookieList.java: CookieList provides support for converting between JSON and
-cookie lists.
-
-HTTP.java: HTTP provides support for converting between JSON and HTTP headers.
-
-HTTPTokener.java: HTTPTokener extends JSONTokener for parsing HTTP headers.
-
-XML.java: XML provides support for converting between JSON and XML.
-
-JSONML.java: JSONML provides support for converting between JSONML and XML.
-
-XMLTokener.java: XMLTokener extends JSONTokener for parsing XML text.
diff --git a/README.md b/README.md
new file mode 100644
index 000000000..206afbb21
--- /dev/null
+++ b/README.md
@@ -0,0 +1,122 @@
+
+
+image credit: Ismael Pérez Ortiz
+
+
+JSON in Java [package org.json]
+===============================
+
+[](https://mvnrepository.com/artifact/org.json/json)
+[](https://github.com/stleary/JSON-java/actions/workflows/pipeline.yml)
+[](https://github.com/stleary/JSON-java/actions/workflows/codeql-analysis.yml)
+
+**[Click here if you just want the latest release jar file.](https://search.maven.org/remotecontent?filepath=org/json/json/20250107/json-20250107.jar)**
+
+
+# Overview
+
+[JSON](http://www.JSON.org/) is a light-weight language-independent data interchange format.
+
+The JSON-Java package is a reference implementation that demonstrates how to parse JSON documents into Java objects and how to generate new JSON documents from the Java classes.
+
+Project goals include:
+* Reliable and consistent results
+* Adherence to the JSON specification
+* Easy to build, use, and include in other projects
+* No external dependencies
+* Fast execution and low memory footprint
+* Maintain backward compatibility
+* Designed and tested to use on Java versions 1.6 - 21
+
+
+The files in this package implement JSON encoders and decoders. The package can also convert between JSON and XML, HTTP headers, Cookies, and CDL.
+
+# If you would like to contribute to this project
+
+For more information on contributions, please see [CONTRIBUTING.md](https://github.com/stleary/JSON-java/blob/master/docs/CONTRIBUTING.md)
+
+Bug fixes, code improvements, and unit test coverage changes are welcome! Because this project is currently in the maintenance phase, the kinds of changes that can be accepted are limited. For more information, please read the [FAQ](https://github.com/stleary/JSON-java/wiki/FAQ).
+
+# Build Instructions
+
+The org.json package can be built from the command line, Maven, and Gradle. The unit tests can be executed from Maven, Gradle, or individually in an IDE e.g. Eclipse.
+
+**Building from the command line**
+
+*Build the class files from the package root directory src/main/java*
+```shell
+javac org/json/*.java
+```
+
+*Create the jar file in the current directory*
+```shell
+jar cf json-java.jar org/json/*.class
+```
+
+*Compile a program that uses the jar (see example code below)*
+```shell
+javac -cp .;json-java.jar Test.java (Windows)
+javac -cp .:json-java.jar Test.java (Unix Systems)
+```
+
+*Test file contents*
+
+```java
+import org.json.JSONObject;
+public class Test {
+ public static void main(String args[]){
+ JSONObject jo = new JSONObject("{ \"abc\" : \"def\" }");
+ System.out.println(jo);
+ }
+}
+```
+
+*Execute the Test file*
+```shell
+java -cp .;json-java.jar Test (Windows)
+java -cp .:json-java.jar Test (Unix Systems)
+```
+
+*Expected output*
+
+```json
+{"abc":"def"}
+```
+
+
+**Tools to build the package and execute the unit tests**
+
+Execute the test suite with Maven:
+```shell
+mvn clean test
+```
+
+Execute the test suite with Gradlew:
+
+```shell
+gradlew clean build test
+```
+
+*Optional* Execute the test suite in strict mode with Gradlew:
+
+```shell
+gradlew testWithStrictMode
+```
+
+*Optional* Execute the test suite in strict mode with Maven:
+
+```shell
+mvn test -P test-strict-mode
+```
+
+# Notes
+
+For more information, please see [NOTES.md](https://github.com/stleary/JSON-java/blob/master/docs/NOTES.md)
+
+# Files
+
+For more information on files, please see [FILES.md](https://github.com/stleary/JSON-java/blob/master/docs/FILES.md)
+
+# Release history:
+
+For the release history, please see [RELEASES.md](https://github.com/stleary/JSON-java/blob/master/docs/RELEASES.md)
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 000000000..5af9a566b
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,5 @@
+# Security Policy
+
+## Reporting a Vulnerability
+
+Please follow the instructions in the ["How are vulnerabilities and exploits handled?"](https://github.com/stleary/JSON-java/wiki/FAQ#how-are-vulnerabilities-and-exploits-handled) section in the FAQ.
diff --git a/XML.java b/XML.java
deleted file mode 100755
index d49784d6d..000000000
--- a/XML.java
+++ /dev/null
@@ -1,508 +0,0 @@
-package org.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.util.Iterator;
-
-
-/**
- * This provides static methods to convert an XML text into a JSONObject,
- * and to covert a JSONObject into an XML text.
- * @author JSON.org
- * @version 2012-10-26
- */
-public class XML {
-
- /** The Character '&'. */
- public static final Character AMP = new Character('&');
-
- /** The Character '''. */
- public static final Character APOS = new Character('\'');
-
- /** The Character '!'. */
- public static final Character BANG = new Character('!');
-
- /** The Character '='. */
- public static final Character EQ = new Character('=');
-
- /** The Character '>'. */
- public static final Character GT = new Character('>');
-
- /** The Character '<'. */
- public static final Character LT = new Character('<');
-
- /** The Character '?'. */
- public static final Character QUEST = new Character('?');
-
- /** The Character '"'. */
- public static final Character QUOT = new Character('"');
-
- /** The Character '/'. */
- public static final Character SLASH = new Character('/');
-
- /**
- * Replace special characters with XML escapes:
- *
- * & (ampersand) is replaced by &
- * < (less than) is replaced by <
- * > (greater than) is replaced by >
- * " (double quote) is replaced by "
- *
- * @param string The string to be escaped.
- * @return The escaped string.
- */
- public static String escape(String string) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0, length = string.length(); i < length; i++) {
- char c = string.charAt(i);
- switch (c) {
- case '&':
- sb.append("&");
- break;
- case '<':
- sb.append("<");
- break;
- case '>':
- sb.append(">");
- break;
- case '"':
- sb.append(""");
- break;
- case '\'':
- sb.append("'");
- break;
- default:
- sb.append(c);
- }
- }
- return sb.toString();
- }
-
- /**
- * Throw an exception if the string contains whitespace.
- * Whitespace is not allowed in tagNames and attributes.
- * @param string
- * @throws JSONException
- */
- public static void noSpace(String string) throws JSONException {
- int i, length = string.length();
- if (length == 0) {
- throw new JSONException("Empty string.");
- }
- for (i = 0; i < length; i += 1) {
- if (Character.isWhitespace(string.charAt(i))) {
- throw new JSONException("'" + string +
- "' contains a space character.");
- }
- }
- }
-
- /**
- * Scan the content following the named tag, attaching it to the context.
- * @param x The XMLTokener containing the source string.
- * @param context The JSONObject that will include the new material.
- * @param name The tag name.
- * @return true if the close tag is processed.
- * @throws JSONException
- */
- private static boolean parse(XMLTokener x, JSONObject context,
- String name) throws JSONException {
- char c;
- int i;
- JSONObject jsonobject = null;
- String string;
- String tagName;
- Object token;
-
-// Test for and skip past these forms:
-//
-//
-//
-// ... ?>
-// Report errors for these forms:
-// <>
-// <=
-// <<
-
- token = x.nextToken();
-
-// ");
- return false;
- }
- x.back();
- } else if (c == '[') {
- token = x.nextToken();
- if ("CDATA".equals(token)) {
- if (x.next() == '[') {
- string = x.nextCDATA();
- if (string.length() > 0) {
- context.accumulate("content", string);
- }
- return false;
- }
- }
- throw x.syntaxError("Expected 'CDATA['");
- }
- i = 1;
- do {
- token = x.nextMeta();
- if (token == null) {
- throw x.syntaxError("Missing '>' after ' 0);
- return false;
- } else if (token == QUEST) {
-
-//
-
- x.skipPast("?>");
- return false;
- } else if (token == SLASH) {
-
-// Close tag
-
- token = x.nextToken();
- if (name == null) {
- throw x.syntaxError("Mismatched close tag " + token);
- }
- if (!token.equals(name)) {
- throw x.syntaxError("Mismatched " + name + " and " + token);
- }
- if (x.nextToken() != GT) {
- throw x.syntaxError("Misshaped close tag");
- }
- return true;
-
- } else if (token instanceof Character) {
- throw x.syntaxError("Misshaped tag");
-
-// Open tag <
-
- } else {
- tagName = (String)token;
- token = null;
- jsonobject = new JSONObject();
- for (;;) {
- if (token == null) {
- token = x.nextToken();
- }
-
-// attribute = value
-
- if (token instanceof String) {
- string = (String)token;
- token = x.nextToken();
- if (token == EQ) {
- token = x.nextToken();
- if (!(token instanceof String)) {
- throw x.syntaxError("Missing value");
- }
- jsonobject.accumulate(string,
- XML.stringToValue((String)token));
- token = null;
- } else {
- jsonobject.accumulate(string, "");
- }
-
-// Empty tag <.../>
-
- } else if (token == SLASH) {
- if (x.nextToken() != GT) {
- throw x.syntaxError("Misshaped tag");
- }
- if (jsonobject.length() > 0) {
- context.accumulate(tagName, jsonobject);
- } else {
- context.accumulate(tagName, "");
- }
- return false;
-
-// Content, between <...> and
-
- } else if (token == GT) {
- for (;;) {
- token = x.nextContent();
- if (token == null) {
- if (tagName != null) {
- throw x.syntaxError("Unclosed tag " + tagName);
- }
- return false;
- } else if (token instanceof String) {
- string = (String)token;
- if (string.length() > 0) {
- jsonobject.accumulate("content",
- XML.stringToValue(string));
- }
-
-// Nested element
-
- } else if (token == LT) {
- if (parse(x, jsonobject, tagName)) {
- if (jsonobject.length() == 0) {
- context.accumulate(tagName, "");
- } else if (jsonobject.length() == 1 &&
- jsonobject.opt("content") != null) {
- context.accumulate(tagName,
- jsonobject.opt("content"));
- } else {
- context.accumulate(tagName, jsonobject);
- }
- return false;
- }
- }
- }
- } else {
- throw x.syntaxError("Misshaped tag");
- }
- }
- }
- }
-
-
- /**
- * Try to convert a string into a number, boolean, or null. If the string
- * can't be converted, return the string. This is much less ambitious than
- * JSONObject.stringToValue, especially because it does not attempt to
- * convert plus forms, octal forms, hex forms, or E forms lacking decimal
- * points.
- * @param string A String.
- * @return A simple JSON value.
- */
- public static Object stringToValue(String string) {
- if ("".equals(string)) {
- return string;
- }
- if ("true".equalsIgnoreCase(string)) {
- return Boolean.TRUE;
- }
- if ("false".equalsIgnoreCase(string)) {
- return Boolean.FALSE;
- }
- if ("null".equalsIgnoreCase(string)) {
- return JSONObject.NULL;
- }
- if ("0".equals(string)) {
- return new Integer(0);
- }
-
-// If it might be a number, try converting it. If that doesn't work,
-// return the string.
-
- try {
- char initial = string.charAt(0);
- boolean negative = false;
- if (initial == '-') {
- initial = string.charAt(1);
- negative = true;
- }
- if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {
- return string;
- }
- if ((initial >= '0' && initial <= '9')) {
- if (string.indexOf('.') >= 0) {
- return Double.valueOf(string);
- } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) {
- Long myLong = new Long(string);
- if (myLong.longValue() == myLong.intValue()) {
- return new Integer(myLong.intValue());
- } else {
- return myLong;
- }
- }
- }
- } catch (Exception ignore) {
- }
- return string;
- }
-
-
- /**
- * Convert a well-formed (but not necessarily valid) XML string into a
- * JSONObject. Some information may be lost in this transformation
- * because JSON is a data format and XML is a document format. XML uses
- * elements, attributes, and content text, while JSON uses unordered
- * collections of name/value pairs and arrays of values. JSON does not
- * does not like to distinguish between elements and attributes.
- * Sequences of similar elements are represented as JSONArrays. Content
- * text may be placed in a "content" member. Comments, prologs, DTDs, and
- * <[ [ ]]> are ignored.
- * @param string The source string.
- * @return A JSONObject containing the structured data from the XML string.
- * @throws JSONException
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- JSONObject jo = new JSONObject();
- XMLTokener x = new XMLTokener(string);
- while (x.more() && x.skipPast("<")) {
- parse(x, jo, null);
- }
- return jo;
- }
-
-
- /**
- * Convert a JSONObject into a well-formed, element-normal XML string.
- * @param object A JSONObject.
- * @return A string.
- * @throws JSONException
- */
- public static String toString(Object object) throws JSONException {
- return toString(object, null);
- }
-
-
- /**
- * Convert a JSONObject into a well-formed, element-normal XML string.
- * @param object A JSONObject.
- * @param tagName The optional name of the enclosing tag.
- * @return A string.
- * @throws JSONException
- */
- public static String toString(Object object, String tagName)
- throws JSONException {
- StringBuffer sb = new StringBuffer();
- int i;
- JSONArray ja;
- JSONObject jo;
- String key;
- Iterator keys;
- int length;
- String string;
- Object value;
- if (object instanceof JSONObject) {
-
-// Emit
-
- if (tagName != null) {
- sb.append('<');
- sb.append(tagName);
- sb.append('>');
- }
-
-// Loop thru the keys.
-
- jo = (JSONObject)object;
- keys = jo.keys();
- while (keys.hasNext()) {
- key = keys.next().toString();
- value = jo.opt(key);
- if (value == null) {
- value = "";
- }
- if (value instanceof String) {
- string = (String)value;
- } else {
- string = null;
- }
-
-// Emit content in body
-
- if ("content".equals(key)) {
- if (value instanceof JSONArray) {
- ja = (JSONArray)value;
- length = ja.length();
- for (i = 0; i < length; i += 1) {
- if (i > 0) {
- sb.append('\n');
- }
- sb.append(escape(ja.get(i).toString()));
- }
- } else {
- sb.append(escape(value.toString()));
- }
-
-// Emit an array of similar keys
-
- } else if (value instanceof JSONArray) {
- ja = (JSONArray)value;
- length = ja.length();
- for (i = 0; i < length; i += 1) {
- value = ja.get(i);
- if (value instanceof JSONArray) {
- sb.append('<');
- sb.append(key);
- sb.append('>');
- sb.append(toString(value));
- sb.append("");
- sb.append(key);
- sb.append('>');
- } else {
- sb.append(toString(value, key));
- }
- }
- } else if ("".equals(value)) {
- sb.append('<');
- sb.append(key);
- sb.append("/>");
-
-// Emit a new tag
-
- } else {
- sb.append(toString(value, key));
- }
- }
- if (tagName != null) {
-
-// Emit the close tag
-
- sb.append("");
- sb.append(tagName);
- sb.append('>');
- }
- return sb.toString();
-
-// XML does not have good support for arrays. If an array appears in a place
-// where XML is lacking, synthesize an element.
-
- } else {
- if (object.getClass().isArray()) {
- object = new JSONArray(object);
- }
- if (object instanceof JSONArray) {
- ja = (JSONArray)object;
- length = ja.length();
- for (i = 0; i < length; i += 1) {
- sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
- }
- return sb.toString();
- } else {
- string = (object == null) ? "null" : escape(object.toString());
- return (tagName == null) ? "\"" + string + "\"" :
- (string.length() == 0) ? "<" + tagName + "/>" :
- "<" + tagName + ">" + string + "" + tagName + ">";
- }
- }
- }
-}
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 000000000..3961e854d
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,127 @@
+/*
+ * This file was generated by the Gradle 'init' task.
+ */
+apply plugin: 'java'
+apply plugin: 'eclipse'
+// apply plugin: 'jacoco'
+apply plugin: 'maven-publish'
+
+//plugins {
+ // id 'java'
+ //id 'maven-publish'
+// }
+
+repositories {
+ mavenLocal()
+ mavenCentral()
+ maven {
+ url = uri('https://oss.sonatype.org/content/repositories/snapshots')
+ }
+}
+
+dependencies {
+ testImplementation 'junit:junit:4.13.2'
+ testImplementation 'com.jayway.jsonpath:json-path:2.9.0'
+ testImplementation 'org.mockito:mockito-core:4.2.0'
+}
+
+subprojects {
+ tasks.withType(Javadoc).all { enabled = false }
+}
+
+group = 'org.json'
+version = 'v20250107-SNAPSHOT'
+description = 'JSON in Java'
+sourceCompatibility = '1.8'
+
+configurations.all {
+}
+
+java {
+ withSourcesJar()
+ withJavadocJar()
+}
+
+publishing {
+ publications {
+ maven(MavenPublication) {
+ from(components.java)
+ }
+ }
+}
+
+tasks.withType(JavaCompile) {
+ options.encoding = 'UTF-8'
+}
+// Add these imports at the top of your build.gradle file
+import java.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.Paths
+import java.nio.file.StandardCopyOption
+
+// Your existing build configurations...
+
+// Add a new task to modify the file
+task modifyStrictMode {
+ doLast {
+ println "Modifying JSONParserConfiguration.java to enable strictMode..."
+
+ def filePath = project.file('src/main/java/org/json/JSONParserConfiguration.java')
+
+ if (!filePath.exists()) {
+ throw new GradleException("Could not find file: ${filePath.absolutePath}")
+ }
+
+ // Create a backup of the original file
+ def backupFile = new File(filePath.absolutePath + '.bak')
+ Files.copy(filePath.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
+
+ // Read and modify the file content
+ def content = filePath.text
+ def modifiedContent = content.replace('// this.strictMode = true;', 'this.strictMode = true;')
+
+ // Write the modified content back to the file
+ filePath.text = modifiedContent
+
+ println "File modified successfully at: ${filePath.absolutePath}"
+ }
+}
+
+// Add a task to restore the original file
+task restoreStrictMode {
+ doLast {
+ println "Restoring original JSONParserConfiguration.java..."
+
+ def filePath = project.file('src/main/java/org/json/JSONParserConfiguration.java')
+ def backupFile = new File(filePath.absolutePath + '.bak')
+
+ if (backupFile.exists()) {
+ Files.copy(backupFile.toPath(), filePath.toPath(), StandardCopyOption.REPLACE_EXISTING)
+ backupFile.delete()
+ println "Original file restored successfully at: ${filePath.absolutePath}"
+ } else {
+ println "Backup file not found at: ${backupFile.absolutePath}. No restoration performed."
+ }
+ }
+}
+
+// Create a task to run the workflow
+task testWithStrictMode {
+ dependsOn modifyStrictMode
+ finalizedBy restoreStrictMode
+
+ doLast {
+ // This will trigger a clean build and run tests with strictMode enabled
+ if (org.gradle.internal.os.OperatingSystem.current().isWindows()) {
+ exec {
+ executable 'cmd'
+ args '/c', 'gradlew.bat', 'clean', 'build'
+ }
+ } else {
+ exec {
+ executable './gradlew'
+ args 'clean', 'build'
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
new file mode 100644
index 000000000..d81ff6147
--- /dev/null
+++ b/docs/CONTRIBUTING.md
@@ -0,0 +1,22 @@
+# Contribution Guidelines
+
+Feel free to work on any issue with a #hacktoberfest label.
+
+If you discover an issue you would like to work on, you can add a new issue to the list. If it meets our criteria, a hacktoberfest label will be added.
+
+# Who is allowed to submit pull requests for this project?
+
+Anyone can submit pull requests for code, tests, or documentation.
+
+# How do you decide which pull requests to accept?
+
+* Does it call out a bug that needs to be fixed? If so, it goes to the top of the list.
+* Does it fix a major user inconvenience? These are given high priority as well.
+* Does it align with the specs? If not, it will probably not be accepted. It turns out there are gray areas in the specs. If this is in a gray area, it will likely be given the benefit of the doubt.
+* Does it break the existing behavior of the lib? If so, it will not be accepted, unless it fixes an egregious bug. This is happening less frequently now.
+
+# For more guidance, see these links:
+
+[README.md (includes build instructions)](https://github.com/stleary/JSON-java#readme)
+
+[FAQ - all your questions answered](https://github.com/stleary/JSON-java/wiki/FAQ)
diff --git a/docs/FILES.md b/docs/FILES.md
new file mode 100644
index 000000000..152272190
--- /dev/null
+++ b/docs/FILES.md
@@ -0,0 +1,62 @@
+# Files
+
+**JSONObject.java**: The `JSONObject` can parse text from a `String` or a `JSONTokener`
+to produce a map-like object. The object provides methods for manipulating its
+contents, and for producing a JSON compliant object serialization.
+
+**JSONArray.java**: The `JSONArray` can parse text from a String or a `JSONTokener`
+to produce a vector-like object. The object provides methods for manipulating
+its contents, and for producing a JSON compliant array serialization.
+
+**JSONTokener.java**: The `JSONTokener` breaks a text into a sequence of individual
+tokens. It can be constructed from a `String`, `Reader`, or `InputStream`. It also can
+parse text from a `String`, `Number`, `Boolean` or `null` like `"hello"`, `42`, `true`,
+`null` to produce a simple json object.
+
+**JSONException.java**: The `JSONException` is the standard exception type thrown
+by this package.
+
+**JSONPointer.java**: Implementation of
+[JSON Pointer (RFC 6901)](https://tools.ietf.org/html/rfc6901). Supports
+JSON Pointers both in the form of string representation and URI fragment
+representation.
+
+**JSONPropertyIgnore.java**: Annotation class that can be used on Java Bean getter methods.
+When used on a bean method that would normally be serialized into a `JSONObject`, it
+overrides the getter-to-key-name logic and forces the property to be excluded from the
+resulting `JSONObject`.
+
+**JSONPropertyName.java**: Annotation class that can be used on Java Bean getter methods.
+When used on a bean method that would normally be serialized into a `JSONObject`, it
+overrides the getter-to-key-name logic and uses the value of the annotation. The Bean
+processor will look through the class hierarchy. This means you can use the annotation on
+a base class or interface and the value of the annotation will be used even if the getter
+is overridden in a child class.
+
+**JSONString.java**: The `JSONString` interface requires a `toJSONString` method,
+allowing an object to provide its own serialization.
+
+**JSONStringer.java**: The `JSONStringer` provides a convenient facility for
+building JSON strings.
+
+**JSONWriter.java**: The `JSONWriter` provides a convenient facility for building
+JSON text through a writer.
+
+
+**CDL.java**: `CDL` provides support for converting between JSON and comma
+delimited lists.
+
+**Cookie.java**: `Cookie` provides support for converting between JSON and cookies.
+
+**CookieList.java**: `CookieList` provides support for converting between JSON and
+cookie lists.
+
+**HTTP.java**: `HTTP` provides support for converting between JSON and HTTP headers.
+
+**HTTPTokener.java**: `HTTPTokener` extends `JSONTokener` for parsing HTTP headers.
+
+**XML.java**: `XML` provides support for converting between JSON and XML.
+
+**JSONML.java**: `JSONML` provides support for converting between JSONML and XML.
+
+**XMLTokener.java**: `XMLTokener` extends `JSONTokener` for parsing XML text.
\ No newline at end of file
diff --git a/docs/NOTES.md b/docs/NOTES.md
new file mode 100644
index 000000000..a8298ddfa
--- /dev/null
+++ b/docs/NOTES.md
@@ -0,0 +1,87 @@
+# Notes
+
+**Recent directory structure change**
+
+_Due to a recent commit - [#515 Merge tests and pom and code](https://github.com/stleary/JSON-java/pull/515) - the structure of the project has changed from a flat directory containing all of the Java files to a directory structure that includes unit tests and several tools used to build the project jar and run the unit tests. If you have difficulty using the new structure, please open an issue so we can work through it._
+
+**Implementation notes**
+
+Numeric types in this package comply with
+[ECMA-404: The JSON Data Interchange Format](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and
+[RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc8259#section-6).
+This package fully supports `Integer`, `Long`, and `Double` Java types. Partial support
+for `BigInteger` and `BigDecimal` values in `JSONObject` and `JSONArray` objects is provided
+in the form of `get()`, `opt()`, and `put()` API methods.
+
+Although 1.6 compatibility is currently supported, it is not a project goal and might be
+removed in some future release.
+
+In compliance with RFC8259 page 10 section 9, the parser is more lax with what is valid
+JSON then the Generator. For Example, the tab character (U+0009) is allowed when reading
+JSON Text strings, but when output by the Generator, the tab is properly converted to \t in
+the string. Other instances may occur where reading invalid JSON text does not cause an
+error to be generated. Malformed JSON Texts such as missing end " (quote) on strings or
+invalid number formats (1.2e6.3) will cause errors as such documents can not be read
+reliably.
+
+Some notable exceptions that the JSON Parser in this library accepts are:
+* Unquoted keys `{ key: "value" }`
+* Unquoted values `{ "key": value }`
+* Unescaped literals like "tab" in string values `{ "key": "value with an unescaped tab" }`
+* Numbers out of range for `Double` or `Long` are parsed as strings
+
+Recent pull requests added a new method `putAll` on the JSONArray. The `putAll` method
+works similarly to other `put` methods in that it does not call `JSONObject.wrap` for items
+added. This can lead to inconsistent object representation in JSONArray structures.
+
+For example, code like this will create a mixed JSONArray, some items wrapped, others
+not:
+
+```java
+SomeBean[] myArr = new SomeBean[]{ new SomeBean(1), new SomeBean(2) };
+// these will be wrapped
+JSONArray jArr = new JSONArray(myArr);
+// these will not be wrapped
+jArr.putAll(new SomeBean[]{ new SomeBean(3), new SomeBean(4) });
+```
+
+For structure consistency, it would be recommended that the above code is changed
+to look like 1 of 2 ways.
+
+Option 1:
+```Java
+SomeBean[] myArr = new SomeBean[]{ new SomeBean(1), new SomeBean(2) };
+JSONArray jArr = new JSONArray();
+// these will not be wrapped
+jArr.putAll(myArr);
+// these will not be wrapped
+jArr.putAll(new SomeBean[]{ new SomeBean(3), new SomeBean(4) });
+// our jArr is now consistent.
+```
+
+Option 2:
+```Java
+SomeBean[] myArr = new SomeBean[]{ new SomeBean(1), new SomeBean(2) };
+// these will be wrapped
+JSONArray jArr = new JSONArray(myArr);
+// these will be wrapped
+jArr.putAll(new JSONArray(new SomeBean[]{ new SomeBean(3), new SomeBean(4) }));
+// our jArr is now consistent.
+```
+
+**Unit Test Conventions**
+
+Test filenames should consist of the name of the module being tested, with the suffix "Test".
+For example, Cookie.java is tested by CookieTest.java.
+
+The fundamental issues with JSON-Java testing are:
+* JSONObjects are unordered, making simple string comparison ineffective.
+* Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject override hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful.
+* Access to the JSONArray and JSONObject internal containers for comparison is not currently available.
+
+General issues with unit testing are:
+* Just writing tests to make coverage goals tends to result in poor tests.
+* Unit tests are a form of documentation - how a given method works is demonstrated by the test. So for a code reviewer or future developer looking at code a good test helps explain how a function is supposed to work according to the original author. This can be difficult if you are not the original developer.
+* It is difficult to evaluate unit tests in a vacuum. You also need to see the code being tested to understand if a test is good.
+* Without unit tests, it is hard to feel confident about the quality of the code, especially when fixing bugs or refactoring. Good tests prevent regressions and keep the intent of the code correct.
+* If you have unit test results along with pull requests, the reviewer has an easier time understanding your code and determining if it works as intended.
\ No newline at end of file
diff --git a/docs/RELEASES.md b/docs/RELEASES.md
new file mode 100644
index 000000000..8e598f929
--- /dev/null
+++ b/docs/RELEASES.md
@@ -0,0 +1,60 @@
+# Release history:
+
+JSON-java releases can be found by searching the Maven repository for groupId "org.json"
+and artifactId "json". For example:
+[https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav](https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav)
+
+~~~
+20250107....Restore moditect in pom.xml
+
+20241224....Strict mode opt-in feature, and recent commits. This release does not contain module-info.class.
+It is not recommended if you need this feature.
+
+20240303 Revert optLong/getLong changes, and recent commits.
+
+20240205 Recent commits.
+
+20231013 First release with minimum Java version 1.8. Recent commits, including fixes for CVE-2023-5072.
+
+20230618 Final release with Java 1.6 compatibility. Future releases will require Java 1.8 or greater.
+
+20230227 Fix for CVE-2022-45688 and recent commits
+
+20220924 New License - public domain, and some minor updates
+
+20220320 Wrap StackOverflow with JSONException
+
+20211205 Recent commits and some bug fixes for similar()
+
+20210307 Recent commits and potentially breaking fix to JSONPointer
+
+20201115 Recent commits and first release after project structure change
+
+20200518 Recent commits and snapshot before project structure change
+
+20190722 Recent commits
+
+20180813 POM change to include Automatic-Module-Name (#431)
+ JSONObject(Map) now throws an exception if any of a map keys are null (#405)
+
+20180130 Recent commits
+
+20171018 Checkpoint for recent commits.
+
+20170516 Roll up recent commits.
+
+20160810 Revert code that was breaking opt*() methods.
+
+20160807 This release contains a bug in the JSONObject.opt*() and JSONArray.opt*() methods,
+it is not recommended for use.
+Java 1.6 compatability fixed, JSONArray.toList() and JSONObject.toMap(),
+RFC4180 compatibility, JSONPointer, some exception fixes, optional XML type conversion.
+Contains the latest code as of 7 Aug 2016
+
+20160212 Java 1.6 compatibility, OSGi bundle. Contains the latest code as of 12 Feb 2016.
+
+20151123 JSONObject and JSONArray initialization with generics. Contains the latest code as of 23 Nov 2015.
+
+20150729 Checkpoint for Maven central repository release. Contains the latest code
+as of 29 July 2015.
+~~~
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
new file mode 100644
index 000000000..5af9a566b
--- /dev/null
+++ b/docs/SECURITY.md
@@ -0,0 +1,5 @@
+# Security Policy
+
+## Reporting a Vulnerability
+
+Please follow the instructions in the ["How are vulnerabilities and exploits handled?"](https://github.com/stleary/JSON-java/wiki/FAQ#how-are-vulnerabilities-and-exploits-handled) section in the FAQ.
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..f3d88b1c2
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..a4b442974
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100755
index 000000000..2fe81a7d9
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,183 @@
+#!/usr/bin/env sh
+
+#
+# Copyright 2015 the original author or authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn () {
+ echo "$*"
+}
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+ NONSTOP* )
+ nonstop=true
+ ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=`expr $i + 1`
+ done
+ case $i in
+ 0) set -- ;;
+ 1) set -- "$args0" ;;
+ 2) set -- "$args0" "$args1" ;;
+ 3) set -- "$args0" "$args1" "$args2" ;;
+ 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Escape application args
+save () {
+ for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
+ echo " "
+}
+APP_ARGS=`save "$@"`
+
+# Collect all arguments for the java command, following the shell quoting and substitution rules
+eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 000000000..9109989e3
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,103 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/images/JsonJava.png b/images/JsonJava.png
new file mode 100644
index 000000000..28c5c9cbc
Binary files /dev/null and b/images/JsonJava.png differ
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 000000000..80c9b89c0
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,254 @@
+
+ 4.0.0
+
+ org.json
+ json
+ 20250107
+ bundle
+
+ JSON in Java
+
+ JSON is a light-weight, language independent, data interchange format.
+ See http://www.JSON.org/
+
+ The files in this package implement JSON encoders/decoders in Java.
+ It also includes the capability to convert between JSON and XML, HTTP
+ headers, Cookies, and CDL.
+
+ This is a reference implementation. There are a large number of JSON packages
+ in Java. Perhaps someday the Java community will standardize on one. Until
+ then, choose carefully.
+
+ https://github.com/douglascrockford/JSON-java
+
+
+ https://github.com/douglascrockford/JSON-java.git
+ scm:git:git://github.com/douglascrockford/JSON-java.git
+ scm:git:git@github.com:douglascrockford/JSON-java.git
+
+
+
+
+ Public Domain
+ https://github.com/stleary/JSON-java/blob/master/LICENSE
+ repo
+
+
+
+
+
+ Douglas Crockford
+ douglas@crockford.com
+
+
+
+
+ UTF-8
+
+
+
+
+
+ ossrh
+ Central Repository OSSRH
+ https://oss.sonatype.org/service/local/staging/deploy/maven2/
+
+
+ ossrh
+ https://oss.sonatype.org/content/repositories/snapshots
+
+
+
+
+
+
+ junit
+ junit
+ 4.13.2
+ test
+
+
+ com.jayway.jsonpath
+ json-path
+ 2.9.0
+ test
+
+
+ org.mockito
+ mockito-core
+ 4.2.0
+ test
+
+
+
+
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ 5.1.9
+ true
+
+
+
+ org.json
+
+ ${project.artifactId}
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.11.0
+
+ 1.8
+ 1.8
+
+ -Xlint:unchecked
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+ 3.3.0
+
+
+ attach-sources
+
+ jar-no-fork
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 3.5.0
+
+
+ attach-javadocs
+
+ jar
+
+
+ -Xdoclint:none
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-gpg-plugin
+ 1.6
+
+
+ sign-artifacts
+ verify
+
+ sign
+
+
+
+ --pinentry-mode
+ loopback
+
+
+
+
+
+
+ org.sonatype.plugins
+ nexus-staging-maven-plugin
+ 1.6.3
+ true
+
+ ossrh
+ https://oss.sonatype.org/
+ false
+
+
+
+ org.moditect
+ moditect-maven-plugin
+ 1.0.0.Final
+
+
+ add-module-infos
+ package
+
+ add-module-info
+
+
+ 9
+
+
+ module org.json {
+ exports org.json;
+ }
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ 3.3.0
+
+
+
+
+
+ test-strict-mode
+
+
+
+ com.google.code.maven-replacer-plugin
+ replacer
+ 1.5.3
+
+
+
+ enable-strict-mode
+ process-sources
+
+ replace
+
+
+ src/main/java/org/json/JSONParserConfiguration.java
+
+
+ // this.strictMode = true;
+ this.strictMode = true;
+
+
+
+
+
+
+ restore-original
+ test
+
+ replace
+
+
+ src/main/java/org/json/JSONParserConfiguration.java
+
+
+ this.strictMode = true;
+ // this.strictMode = true;
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/json/CDL.java b/src/main/java/org/json/CDL.java
new file mode 100644
index 000000000..dd631bf8f
--- /dev/null
+++ b/src/main/java/org/json/CDL.java
@@ -0,0 +1,397 @@
+package org.json;
+
+/*
+Public Domain.
+ */
+
+/**
+ * This provides static methods to convert comma (or otherwise) delimited text into a
+ * JSONArray, and to convert a JSONArray into comma (or otherwise) delimited text. Comma
+ * delimited text is a very popular format for data interchange. It is
+ * understood by most database, spreadsheet, and organizer programs.
+ *
+ * Each row of text represents a row in a table or a data record. Each row
+ * ends with a NEWLINE character. Each row contains one or more values.
+ * Values are separated by commas. A value can contain any character except
+ * for comma, unless it is wrapped in single quotes or double quotes.
+ *
+ * The first row usually contains the names of the columns.
+ *
+ * A comma delimited list can be converted into a JSONArray of JSONObjects.
+ * The names for the elements in the JSONObjects can be taken from the names
+ * in the first row.
+ * @author JSON.org
+ * @version 2016-05-01
+ */
+public class CDL {
+
+ /**
+ * Constructs a new CDL object.
+ */
+ public CDL() {
+ }
+
+ /**
+ * Get the next value. The value can be wrapped in quotes. The value can
+ * be empty.
+ * @param x A JSONTokener of the source text.
+ * @param delimiter used in the file
+ * @return The value string, or null if empty.
+ * @throws JSONException if the quoted string is badly formed.
+ */
+ private static String getValue(JSONTokener x, char delimiter) throws JSONException {
+ char c;
+ char q;
+ StringBuilder sb;
+ do {
+ c = x.next();
+ } while (c == ' ' || c == '\t');
+ if (c == 0) {
+ return null;
+ } else if (c == '"' || c == '\'') {
+ q = c;
+ sb = new StringBuilder();
+ for (;;) {
+ c = x.next();
+ if (c == q) {
+ //Handle escaped double-quote
+ char nextC = x.next();
+ if (nextC != '\"') {
+ // if our quote was the end of the file, don't step
+ if (nextC > 0) {
+ x.back();
+ }
+ break;
+ }
+ }
+ if (c == 0 || c == '\n' || c == '\r') {
+ throw x.syntaxError("Missing close quote '" + q + "'.");
+ }
+ sb.append(c);
+ }
+ return sb.toString();
+ } else if (c == delimiter) {
+ x.back();
+ return "";
+ }
+ x.back();
+ return x.nextTo(delimiter);
+ }
+
+ /**
+ * Produce a JSONArray of strings from a row of comma delimited values.
+ * @param x A JSONTokener of the source text.
+ * @return A JSONArray of strings.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
+ return rowToJSONArray(x, ',');
+ }
+
+ /**
+ * Produce a JSONArray of strings from a row of comma delimited values.
+ * @param x A JSONTokener of the source text.
+ * @param delimiter custom delimiter char
+ * @return A JSONArray of strings.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray rowToJSONArray(JSONTokener x, char delimiter) throws JSONException {
+ JSONArray ja = new JSONArray();
+ for (;;) {
+ String value = getValue(x,delimiter);
+ char c = x.next();
+ if (value != null) {
+ ja.put(value);
+ } else if (ja.length() == 0 && c != delimiter) {
+ return null;
+ } else {
+ // This line accounts for CSV ending with no newline
+ ja.put("");
+ }
+
+ for (;;) {
+ if (c == delimiter) {
+ break;
+ }
+ if (c != ' ') {
+ if (c == '\n' || c == '\r' || c == 0) {
+ return ja;
+ }
+ throw x.syntaxError("Bad character '" + c + "' (" +
+ (int)c + ").");
+ }
+ c = x.next();
+ }
+ }
+ }
+
+ /**
+ * Produce a JSONObject from a row of comma delimited text, using a
+ * parallel JSONArray of strings to provides the names of the elements.
+ * @param names A JSONArray of names. This is commonly obtained from the
+ * first row of a comma delimited text file using the rowToJSONArray
+ * method.
+ * @param x A JSONTokener of the source text.
+ * @return A JSONObject combining the names and values.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException {
+ return rowToJSONObject(names, x, ',');
+ }
+
+ /**
+ * Produce a JSONObject from a row of comma delimited text, using a
+ * parallel JSONArray of strings to provides the names of the elements.
+ * @param names A JSONArray of names. This is commonly obtained from the
+ * first row of a comma delimited text file using the rowToJSONArray
+ * method.
+ * @param x A JSONTokener of the source text.
+ * @param delimiter custom delimiter char
+ * @return A JSONObject combining the names and values.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x, char delimiter) throws JSONException {
+ JSONArray ja = rowToJSONArray(x, delimiter);
+ return ja != null ? ja.toJSONObject(names) : null;
+ }
+
+ /**
+ * Produce a comma delimited text row from a JSONArray. Values containing
+ * the comma character will be quoted. Troublesome characters may be
+ * removed.
+ * @param ja A JSONArray of strings.
+ * @return A string ending in NEWLINE.
+ */
+ public static String rowToString(JSONArray ja) {
+ return rowToString(ja, ',');
+ }
+
+ /**
+ * Produce a comma delimited text row from a JSONArray. Values containing
+ * the comma character will be quoted. Troublesome characters may be
+ * removed.
+ * @param ja A JSONArray of strings.
+ * @param delimiter custom delimiter char
+ * @return A string ending in NEWLINE.
+ */
+ public static String rowToString(JSONArray ja, char delimiter) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < ja.length(); i += 1) {
+ if (i > 0) {
+ sb.append(delimiter);
+ }
+ Object object = ja.opt(i);
+ if (object != null) {
+ String string = object.toString();
+ if (string.length() > 0 && (string.indexOf(delimiter) >= 0 ||
+ string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
+ string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
+ sb.append('"');
+ int length = string.length();
+ for (int j = 0; j < length; j += 1) {
+ char c = string.charAt(j);
+ if (c >= ' ' && c != '"') {
+ sb.append(c);
+ }
+ }
+ sb.append('"');
+ } else {
+ sb.append(string);
+ }
+ }
+ }
+ sb.append('\n');
+ return sb.toString();
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string,
+ * using the first row as a source of names.
+ * @param string The comma delimited text.
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray toJSONArray(String string) throws JSONException {
+ return toJSONArray(string, ',');
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string,
+ * using the first row as a source of names.
+ * @param string The comma delimited text.
+ * @param delimiter custom delimiter char
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray toJSONArray(String string, char delimiter) throws JSONException {
+ return toJSONArray(new JSONTokener(string), delimiter);
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string,
+ * using the first row as a source of names.
+ * @param x The JSONTokener containing the comma delimited text.
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
+ return toJSONArray(x, ',');
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string,
+ * using the first row as a source of names.
+ * @param x The JSONTokener containing the comma delimited text.
+ * @param delimiter custom delimiter char
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray toJSONArray(JSONTokener x, char delimiter) throws JSONException {
+ return toJSONArray(rowToJSONArray(x, delimiter), x, delimiter);
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string
+ * using a supplied JSONArray as the source of element names.
+ * @param names A JSONArray of strings.
+ * @param string The comma delimited text.
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException {
+ return toJSONArray(names, string, ',');
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string
+ * using a supplied JSONArray as the source of element names.
+ * @param names A JSONArray of strings.
+ * @param string The comma delimited text.
+ * @param delimiter custom delimiter char
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray toJSONArray(JSONArray names, String string, char delimiter) throws JSONException {
+ return toJSONArray(names, new JSONTokener(string), delimiter);
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string
+ * using a supplied JSONArray as the source of element names.
+ * @param names A JSONArray of strings.
+ * @param x A JSONTokener of the source text.
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException {
+ return toJSONArray(names, x, ',');
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string
+ * using a supplied JSONArray as the source of element names.
+ * @param names A JSONArray of strings.
+ * @param x A JSONTokener of the source text.
+ * @param delimiter custom delimiter char
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONArray toJSONArray(JSONArray names, JSONTokener x, char delimiter) throws JSONException {
+ if (names == null || names.length() == 0) {
+ return null;
+ }
+ JSONArray ja = new JSONArray();
+ for (;;) {
+ JSONObject jo = rowToJSONObject(names, x, delimiter);
+ if (jo == null) {
+ break;
+ }
+ ja.put(jo);
+ }
+ if (ja.length() == 0) {
+ return null;
+ }
+
+ // The following block accounts for empty datasets (no keys or vals)
+ if (ja.length() == 1) {
+ JSONObject j = ja.getJSONObject(0);
+ if (j.length() == 1) {
+ String key = j.keys().next();
+ if ("".equals(key) && "".equals(j.get(key))) {
+ return null;
+ }
+ }
+ }
+ return ja;
+ }
+
+
+ /**
+ * Produce a comma delimited text from a JSONArray of JSONObjects. The
+ * first row will be a list of names obtained by inspecting the first
+ * JSONObject.
+ * @param ja A JSONArray of JSONObjects.
+ * @return A comma delimited text.
+ * @throws JSONException if a called function fails
+ */
+ public static String toString(JSONArray ja) throws JSONException {
+ return toString(ja, ',');
+ }
+
+ /**
+ * Produce a comma delimited text from a JSONArray of JSONObjects. The
+ * first row will be a list of names obtained by inspecting the first
+ * JSONObject.
+ * @param ja A JSONArray of JSONObjects.
+ * @param delimiter custom delimiter char
+ * @return A comma delimited text.
+ * @throws JSONException if a called function fails
+ */
+ public static String toString(JSONArray ja, char delimiter) throws JSONException {
+ JSONObject jo = ja.optJSONObject(0);
+ if (jo != null) {
+ JSONArray names = jo.names();
+ if (names != null) {
+ return rowToString(names, delimiter) + toString(names, ja, delimiter);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Produce a comma delimited text from a JSONArray of JSONObjects using
+ * a provided list of names. The list of names is not included in the
+ * output.
+ * @param names A JSONArray of strings.
+ * @param ja A JSONArray of JSONObjects.
+ * @return A comma delimited text.
+ * @throws JSONException if a called function fails
+ */
+ public static String toString(JSONArray names, JSONArray ja) throws JSONException {
+ return toString(names, ja, ',');
+ }
+
+ /**
+ * Produce a comma delimited text from a JSONArray of JSONObjects using
+ * a provided list of names. The list of names is not included in the
+ * output.
+ * @param names A JSONArray of strings.
+ * @param ja A JSONArray of JSONObjects.
+ * @param delimiter custom delimiter char
+ * @return A comma delimited text.
+ * @throws JSONException if a called function fails
+ */
+ public static String toString(JSONArray names, JSONArray ja, char delimiter) throws JSONException {
+ if (names == null || names.length() == 0) {
+ return null;
+ }
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < ja.length(); i += 1) {
+ JSONObject jo = ja.optJSONObject(i);
+ if (jo != null) {
+ sb.append(rowToString(jo.toJSONArray(names), delimiter));
+ }
+ }
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/org/json/Cookie.java b/src/main/java/org/json/Cookie.java
new file mode 100644
index 000000000..ab908a304
--- /dev/null
+++ b/src/main/java/org/json/Cookie.java
@@ -0,0 +1,210 @@
+package org.json;
+
+import java.util.Locale;
+
+/*
+Public Domain.
+*/
+
+/**
+ * Convert a web browser cookie specification to a JSONObject and back.
+ * JSON and Cookies are both notations for name/value pairs.
+ * See also: https://tools.ietf.org/html/rfc6265
+ * @author JSON.org
+ * @version 2015-12-09
+ */
+public class Cookie {
+
+ /**
+ * Constructs a new Cookie object.
+ */
+ public Cookie() {
+ }
+
+ /**
+ * Produce a copy of a string in which the characters '+', '%', '=', ';'
+ * and control characters are replaced with "%hh". This is a gentle form
+ * of URL encoding, attempting to cause as little distortion to the
+ * string as possible. The characters '=' and ';' are meta characters in
+ * cookies. By convention, they are escaped using the URL-encoding. This is
+ * only a convention, not a standard. Often, cookies are expected to have
+ * encoded values. We encode '=' and ';' because we must. We encode '%' and
+ * '+' because they are meta characters in URL encoding.
+ * @param string The source string.
+ * @return The escaped result.
+ */
+ public static String escape(String string) {
+ char c;
+ String s = string.trim();
+ int length = s.length();
+ StringBuilder sb = new StringBuilder(length);
+ for (int i = 0; i < length; i += 1) {
+ c = s.charAt(i);
+ if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
+ sb.append('%');
+ sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
+ sb.append(Character.forDigit((char)(c & 0x0f), 16));
+ } else {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+
+
+ /**
+ * Convert a cookie specification string into a JSONObject. The string
+ * must contain a name value pair separated by '='. The name and the value
+ * will be unescaped, possibly converting '+' and '%' sequences. The
+ * cookie properties may follow, separated by ';', also represented as
+ * name=value (except the Attribute properties like "Secure" or "HttpOnly",
+ * which do not have a value. The value {@link Boolean#TRUE} will be used for these).
+ * The name will be stored under the key "name", and the value will be
+ * stored under the key "value". This method does not do checking or
+ * validation of the parameters. It only converts the cookie string into
+ * a JSONObject. All attribute names are converted to lower case keys in the
+ * JSONObject (HttpOnly => httponly). If an attribute is specified more than
+ * once, only the value found closer to the end of the cookie-string is kept.
+ * @param string The cookie specification string.
+ * @return A JSONObject containing "name", "value", and possibly other
+ * members.
+ * @throws JSONException If there is an error parsing the Cookie String.
+ * Cookie strings must have at least one '=' character and the 'name'
+ * portion of the cookie must not be blank.
+ */
+ public static JSONObject toJSONObject(String string) {
+ final JSONObject jo = new JSONObject();
+ String name;
+ Object value;
+
+
+ JSONTokener x = new JSONTokener(string);
+
+ name = unescape(x.nextTo('=').trim());
+ //per RFC6265, if the name is blank, the cookie should be ignored.
+ if("".equals(name)) {
+ throw new JSONException("Cookies must have a 'name'");
+ }
+ jo.put("name", name);
+ // per RFC6265, if there is no '=', the cookie should be ignored.
+ // the 'next' call here throws an exception if the '=' is not found.
+ x.next('=');
+ jo.put("value", unescape(x.nextTo(';')).trim());
+ // discard the ';'
+ x.next();
+ // parse the remaining cookie attributes
+ while (x.more()) {
+ name = unescape(x.nextTo("=;")).trim().toLowerCase(Locale.ROOT);
+ // don't allow a cookies attributes to overwrite its name or value.
+ if("name".equalsIgnoreCase(name)) {
+ throw new JSONException("Illegal attribute name: 'name'");
+ }
+ if("value".equalsIgnoreCase(name)) {
+ throw new JSONException("Illegal attribute name: 'value'");
+ }
+ // check to see if it's a flag property
+ if (x.next() != '=') {
+ value = Boolean.TRUE;
+ } else {
+ value = unescape(x.nextTo(';')).trim();
+ x.next();
+ }
+ // only store non-blank attributes
+ if(!"".equals(name) && !"".equals(value)) {
+ jo.put(name, value);
+ }
+ }
+ return jo;
+ }
+
+
+ /**
+ * Convert a JSONObject into a cookie specification string. The JSONObject
+ * must contain "name" and "value" members (case insensitive).
+ * If the JSONObject contains other members, they will be appended to the cookie
+ * specification string. User-Agents are instructed to ignore unknown attributes,
+ * so ensure your JSONObject is using only known attributes.
+ * See also: https://tools.ietf.org/html/rfc6265
+ * @param jo A JSONObject
+ * @return A cookie specification string
+ * @throws JSONException thrown if the cookie has no name.
+ */
+ public static String toString(JSONObject jo) throws JSONException {
+ StringBuilder sb = new StringBuilder();
+
+ String name = null;
+ Object value = null;
+ for(String key : jo.keySet()){
+ if("name".equalsIgnoreCase(key)) {
+ name = jo.getString(key).trim();
+ }
+ if("value".equalsIgnoreCase(key)) {
+ value=jo.getString(key).trim();
+ }
+ if(name != null && value != null) {
+ break;
+ }
+ }
+
+ if(name == null || "".equals(name.trim())) {
+ throw new JSONException("Cookie does not have a name");
+ }
+ if(value == null) {
+ value = "";
+ }
+
+ sb.append(escape(name));
+ sb.append("=");
+ sb.append(escape((String)value));
+
+ for(String key : jo.keySet()){
+ if("name".equalsIgnoreCase(key)
+ || "value".equalsIgnoreCase(key)) {
+ // already processed above
+ continue;
+ }
+ value = jo.opt(key);
+ if(value instanceof Boolean) {
+ if(Boolean.TRUE.equals(value)) {
+ sb.append(';').append(escape(key));
+ }
+ // don't emit false values
+ } else {
+ sb.append(';')
+ .append(escape(key))
+ .append('=')
+ .append(escape(value.toString()));
+ }
+ }
+
+ return sb.toString();
+ }
+
+ /**
+ * Convert %hh sequences to single characters, and
+ * convert plus to space.
+ * @param string A string that may contain
+ * + (plus) and
+ * %hh sequences.
+ * @return The unescaped string.
+ */
+ public static String unescape(String string) {
+ int length = string.length();
+ StringBuilder sb = new StringBuilder(length);
+ for (int i = 0; i < length; ++i) {
+ char c = string.charAt(i);
+ if (c == '+') {
+ c = ' ';
+ } else if (c == '%' && i + 2 < length) {
+ int d = JSONTokener.dehexchar(string.charAt(i + 1));
+ int e = JSONTokener.dehexchar(string.charAt(i + 2));
+ if (d >= 0 && e >= 0) {
+ c = (char)(d * 16 + e);
+ i += 2;
+ }
+ }
+ sb.append(c);
+ }
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/org/json/CookieList.java b/src/main/java/org/json/CookieList.java
new file mode 100644
index 000000000..d1064db52
--- /dev/null
+++ b/src/main/java/org/json/CookieList.java
@@ -0,0 +1,72 @@
+package org.json;
+
+/*
+Public Domain.
+ */
+
+/**
+ * Convert a web browser cookie list string to a JSONObject and back.
+ * @author JSON.org
+ * @version 2015-12-09
+ */
+public class CookieList {
+
+ /**
+ * Constructs a new CookieList object.
+ */
+ public CookieList() {
+ }
+
+ /**
+ * Convert a cookie list into a JSONObject. A cookie list is a sequence
+ * of name/value pairs. The names are separated from the values by '='.
+ * The pairs are separated by ';'. The names and the values
+ * will be unescaped, possibly converting '+' and '%' sequences.
+ *
+ * To add a cookie to a cookie list,
+ * cookielistJSONObject.put(cookieJSONObject.getString("name"),
+ * cookieJSONObject.getString("value"));
+ * @param string A cookie list string
+ * @return A JSONObject
+ * @throws JSONException if a called function fails
+ */
+ public static JSONObject toJSONObject(String string) throws JSONException {
+ JSONObject jo = new JSONObject();
+ JSONTokener x = new JSONTokener(string);
+ while (x.more()) {
+ String name = Cookie.unescape(x.nextTo('='));
+ x.next('=');
+ jo.put(name, Cookie.unescape(x.nextTo(';')));
+ x.next();
+ }
+ return jo;
+ }
+
+ /**
+ * Convert a JSONObject into a cookie list. A cookie list is a sequence
+ * of name/value pairs. The names are separated from the values by '='.
+ * The pairs are separated by ';'. The characters '%', '+', '=', and ';'
+ * in the names and values are replaced by "%hh".
+ * @param jo A JSONObject
+ * @return A cookie list string
+ * @throws JSONException if a called function fails
+ */
+ public static String toString(JSONObject jo) throws JSONException {
+ boolean isEndOfPair = false;
+ final StringBuilder sb = new StringBuilder();
+ // Don't use the new entrySet API to maintain Android support
+ for (final String key : jo.keySet()) {
+ final Object value = jo.opt(key);
+ if (!JSONObject.NULL.equals(value)) {
+ if (isEndOfPair) {
+ sb.append(';');
+ }
+ sb.append(Cookie.escape(key));
+ sb.append("=");
+ sb.append(Cookie.escape(value.toString()));
+ isEndOfPair = true;
+ }
+ }
+ return sb.toString();
+ }
+}
diff --git a/HTTP.java b/src/main/java/org/json/HTTP.java
old mode 100755
new mode 100644
similarity index 65%
rename from HTTP.java
rename to src/main/java/org/json/HTTP.java
index 43d04a804..44ab3a6d3
--- a/HTTP.java
+++ b/src/main/java/org/json/HTTP.java
@@ -1,163 +1,148 @@
-package org.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.util.Iterator;
-
-/**
- * Convert an HTTP header to a JSONObject and back.
- * @author JSON.org
- * @version 2010-12-24
- */
-public class HTTP {
-
- /** Carriage return/line feed. */
- public static final String CRLF = "\r\n";
-
- /**
- * Convert an HTTP header string into a JSONObject. It can be a request
- * header or a response header. A request header will contain
- *
- * It does no further checking or conversion. It does not parse dates.
- * It does not do '%' transforms on URLs.
- * @param string An HTTP header string.
- * @return A JSONObject containing the elements and attributes
- * of the XML string.
- * @throws JSONException
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- JSONObject jo = new JSONObject();
- HTTPTokener x = new HTTPTokener(string);
- String token;
-
- token = x.nextToken();
- if (token.toUpperCase().startsWith("HTTP")) {
-
-// Response
-
- jo.put("HTTP-Version", token);
- jo.put("Status-Code", x.nextToken());
- jo.put("Reason-Phrase", x.nextTo('\0'));
- x.next();
-
- } else {
-
-// Request
-
- jo.put("Method", token);
- jo.put("Request-URI", x.nextToken());
- jo.put("HTTP-Version", x.nextToken());
- }
-
-// Fields
-
- while (x.more()) {
- String name = x.nextTo(':');
- x.next(':');
- jo.put(name, x.nextTo('\0'));
- x.next();
- }
- return jo;
- }
-
-
- /**
- * Convert a JSONObject into an HTTP header. A request header must contain
- *
+ * It does no further checking or conversion. It does not parse dates.
+ * It does not do '%' transforms on URLs.
+ * @param string An HTTP header string.
+ * @return A JSONObject containing the elements and attributes
+ * of the XML string.
+ * @throws JSONException if a called function fails
+ */
+ public static JSONObject toJSONObject(String string) throws JSONException {
+ JSONObject jo = new JSONObject();
+ HTTPTokener x = new HTTPTokener(string);
+ String token;
+
+ token = x.nextToken();
+ if (token.toUpperCase(Locale.ROOT).startsWith("HTTP")) {
+
+// Response
+
+ jo.put("HTTP-Version", token);
+ jo.put("Status-Code", x.nextToken());
+ jo.put("Reason-Phrase", x.nextTo('\0'));
+ x.next();
+
+ } else {
+
+// Request
+
+ jo.put("Method", token);
+ jo.put("Request-URI", x.nextToken());
+ jo.put("HTTP-Version", x.nextToken());
+ }
+
+// Fields
+
+ while (x.more()) {
+ String name = x.nextTo(':');
+ x.next(':');
+ jo.put(name, x.nextTo('\0'));
+ x.next();
+ }
+ return jo;
+ }
+
+
+ /**
+ * Convert a JSONObject into an HTTP header. A request header must contain
+ *
+ * Any other members of the JSONObject will be output as HTTP fields.
+ * The result will end with two CRLF pairs.
+ * @param jo A JSONObject
+ * @return An HTTP header string.
+ * @throws JSONException if the object does not contain enough
+ * information.
+ */
+ public static String toString(JSONObject jo) throws JSONException {
+ StringBuilder sb = new StringBuilder();
+ if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {
+ sb.append(jo.getString("HTTP-Version"));
+ sb.append(' ');
+ sb.append(jo.getString("Status-Code"));
+ sb.append(' ');
+ sb.append(jo.getString("Reason-Phrase"));
+ } else if (jo.has("Method") && jo.has("Request-URI")) {
+ sb.append(jo.getString("Method"));
+ sb.append(' ');
+ sb.append('"');
+ sb.append(jo.getString("Request-URI"));
+ sb.append('"');
+ sb.append(' ');
+ sb.append(jo.getString("HTTP-Version"));
+ } else {
+ throw new JSONException("Not enough material for an HTTP header.");
+ }
+ sb.append(CRLF);
+ // Don't use the new entrySet API to maintain Android support
+ for (final String key : jo.keySet()) {
+ String value = jo.optString(key);
+ if (!"HTTP-Version".equals(key) && !"Status-Code".equals(key) &&
+ !"Reason-Phrase".equals(key) && !"Method".equals(key) &&
+ !"Request-URI".equals(key) && !JSONObject.NULL.equals(value)) {
+ sb.append(key);
+ sb.append(": ");
+ sb.append(jo.optString(key));
+ sb.append(CRLF);
+ }
+ }
+ sb.append(CRLF);
+ return sb.toString();
+ }
+}
diff --git a/HTTPTokener.java b/src/main/java/org/json/HTTPTokener.java
old mode 100755
new mode 100644
similarity index 50%
rename from HTTPTokener.java
rename to src/main/java/org/json/HTTPTokener.java
index ed41744a0..48cad31a3
--- a/HTTPTokener.java
+++ b/src/main/java/org/json/HTTPTokener.java
@@ -1,34 +1,14 @@
package org.json;
/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+Public Domain.
*/
/**
* The HTTPTokener extends the JSONTokener to provide additional methods
* for the parsing of HTTP headers.
* @author JSON.org
- * @version 2012-11-13
+ * @version 2015-12-09
*/
public class HTTPTokener extends JSONTokener {
@@ -43,13 +23,13 @@ public HTTPTokener(String string) {
/**
* Get the next token or string. This is used in parsing HTTP headers.
- * @throws JSONException
* @return A String.
+ * @throws JSONException if a syntax error occurs
*/
public String nextToken() throws JSONException {
char c;
char q;
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
do {
c = next();
} while (Character.isWhitespace(c));
diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java
new file mode 100644
index 000000000..e2725b7a9
--- /dev/null
+++ b/src/main/java/org/json/JSONArray.java
@@ -0,0 +1,2026 @@
+package org.json;
+
+/*
+Public Domain.
+ */
+
+import java.io.IOException;
+import java.io.Writer;
+import java.lang.reflect.Array;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * A JSONArray is an ordered sequence of values. Its external text form is a
+ * string wrapped in square brackets with commas separating the values. The
+ * internal form is an object having get and opt
+ * methods for accessing the values by index, and put methods for
+ * adding or replacing values. The values can be any of these types:
+ * Boolean, JSONArray, JSONObject,
+ * Number, String, or the
+ * JSONObject.NULL object.
+ *
+ * The constructor can convert a JSON text into a Java object. The
+ * toString method converts to JSON text.
+ *
+ * A get method returns a value if one can be found, and throws an
+ * exception if one cannot be found. An opt method returns a
+ * default value instead of throwing an exception, and so is useful for
+ * obtaining optional values.
+ *
+ * The generic get() and opt() methods return an
+ * object which you can cast or query for type. There are also typed
+ * get and opt methods that do type checking and type
+ * coercion for you.
+ *
+ * The texts produced by the toString methods strictly conform to
+ * JSON syntax rules. The constructors are more forgiving in the texts they will
+ * accept:
+ *
+ *
An extra , (comma) may appear just
+ * before the closing bracket.
+ *
The null value will be inserted when there is ,
+ * (comma) elision.
+ *
Strings may be quoted with ' (single
+ * quote).
+ *
Strings do not need to be quoted at all if they do not begin with a quote
+ * or single quote, and if they do not contain leading or trailing spaces, and
+ * if they do not contain any of these characters:
+ * { } [ ] / \ : , # and if they do not look like numbers and
+ * if they are not the reserved words true, false, or
+ * null.