diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
new file mode 100644
index 000000000..693699456
--- /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@v3
+ 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@v3
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
new file mode 100644
index 000000000..85aea5501
--- /dev/null
+++ b/.github/workflows/pipeline.yml
@@ -0,0 +1,277 @@
+# 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@v5
+ - 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@v5
+ 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@v5
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v5
+ 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@v5
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v5
+ 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@v5
+ 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@v5
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v5
+ 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@v5
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v5
+ 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@v5
+ 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@v5
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v5
+ 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@v5
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v5
+ 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@v5
+ 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@v5
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v5
+ 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@v5
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v5
+ 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@v5
+ with:
+ name: Package Jar ${{ matrix.java }}
+ path: target/*.jar
+
+ build-25:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ max-parallel: 1
+ matrix:
+ # build against supported Java LTS versions:
+ java: [ 25 ]
+ name: Java ${{ matrix.java }}
+ steps:
+ - uses: actions/checkout@v5
+ - name: Set up JDK ${{ matrix.java }}
+ uses: actions/setup-java@v5
+ 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@v5
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v5
+ 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@v5
+ with:
+ name: Package Jar ${{ matrix.java }}
+ path: target/*.jar
+
diff --git a/.gitignore b/.gitignore
index 50b216e17..b78af4db7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +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 100644
index 1c7df3223..000000000
--- a/CDL.java
+++ /dev/null
@@ -1,287 +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 convert 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 2016-05-01
- */
-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) {
- //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();
- 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) {
- StringBuilder sb = new StringBuilder();
- 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 100644
index 348dc688d..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 2015-12-09
- */
-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();
- 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
- * 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 {
- StringBuilder sb = new StringBuilder();
-
- 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();
- 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/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/JSONPointerException.java b/JSONPointerException.java
deleted file mode 100644
index 0ce1aeb29..000000000
--- a/JSONPointerException.java
+++ /dev/null
@@ -1,45 +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.
-*/
-
-/**
- * The JSONPointerException is thrown by {@link JSONPointer} if an error occurs
- * during evaluating a pointer.
- *
- * @author JSON.org
- * @version 2016-05-13
- */
-public class JSONPointerException extends JSONException {
- private static final long serialVersionUID = 8872944667561856751L;
-
- public JSONPointerException(String message) {
- super(message);
- }
-
- public JSONPointerException(String message, Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/JSONPropertyIgnore.java b/JSONPropertyIgnore.java
deleted file mode 100644
index 682de7447..000000000
--- a/JSONPropertyIgnore.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package org.json;
-
-/*
-Copyright (c) 2018 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 static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Documented;
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-@Documented
-@Retention(RUNTIME)
-@Target({METHOD})
-/**
- * Use this annotation on a getter method to override the Bean name
- * parser for Bean -> JSONObject mapping. If this annotation is
- * present at any level in the class hierarchy, then the method will
- * not be serialized from the bean into the JSONObject.
- */
-public @interface JSONPropertyIgnore { }
diff --git a/JSONPropertyName.java b/JSONPropertyName.java
deleted file mode 100644
index a1bcd58bf..000000000
--- a/JSONPropertyName.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package org.json;
-
-/*
-Copyright (c) 2018 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 static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Documented;
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-@Documented
-@Retention(RUNTIME)
-@Target({METHOD})
-/**
- * Use this annotation on a getter method to override the Bean name
- * parser for Bean -> JSONObject mapping. A value set to empty string ""
- * will have the Bean parser fall back to the default field name processing.
- */
-public @interface JSONPropertyName {
- /**
- * @return The name of the property as to be used in the JSON Object.
- */
- String value();
-}
diff --git a/LICENSE b/LICENSE
index 02ee0efa2..2ef9799e0 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,23 +1,2 @@
-============================================================================
+Public Domain.
-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.
diff --git a/README.md b/README.md
index 82ffedcf3..5cc3bd451 100644
--- a/README.md
+++ b/README.md
@@ -1,136 +1,123 @@
-JSON in Java [package org.json]
-===============================
-
-[](https://mvnrepository.com/artifact/org.json/json)
-
-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.
+image credit: Ismael Pérez Ortiz
-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.6-1.8.
+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)
+[](https://javadoc.io/doc/org.json/json)
-**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.
+**[Click here if you just want the latest release jar file.](https://search.maven.org/remotecontent?filepath=org/json/json/20251224/json-20251224.jar)**
-**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`.
+# Overview
-**JSONException.java**: The `JSONException` is the standard exception type thrown
-by this package.
+[JSON](http://www.JSON.org/) is a light-weight language-independent data interchange format.
-**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.
+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.
-**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`.
+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 - 25
-**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.
+The files in this package implement JSON encoders and decoders. The package can also convert between JSON and XML, HTTP headers, Cookies, and CDL.
-**JSONStringer.java**: The `JSONStringer` provides a convenient facility for
-building JSON strings.
+# If you would like to contribute to this project
-**JSONWriter.java**: The `JSONWriter` provides a convenient facility for building
-JSON text through a writer.
+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).
-**CDL.java**: `CDL` provides support for converting between JSON and comma
-delimited lists.
+# Build Instructions
-**Cookie.java**: `Cookie` provides support for converting between JSON and cookies.
+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**
-**CookieList.java**: `CookieList` provides support for converting between JSON and
-cookie lists.
+*Build the class files from the package root directory src/main/java*
+```shell
+javac org/json/*.java
+```
-**HTTP.java**: `HTTP` provides support for converting between JSON and HTTP headers.
+*Create the jar file in the current directory*
+```shell
+jar cf json-java.jar org/json/*.class
+```
-**HTTPTokener.java**: `HTTPTokener` extends `JSONTokener` for parsing HTTP headers.
+*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)
+```
-**XML.java**: `XML` provides support for converting between JSON and XML.
+*Test file contents*
-**JSONML.java**: `JSONML` provides support for converting between JSONML and XML.
+```java
+import org.json.JSONObject;
+public class Test {
+ public static void main(String args[]){
+ JSONObject jo = new JSONObject("{ \"abc\" : \"def\" }");
+ System.out.println(jo);
+ }
+}
+```
-**XMLTokener.java**: `XMLTokener` extends `JSONTokener` for parsing XML text.
+*Execute the Test file*
+```shell
+java -cp .;json-java.jar Test (Windows)
+java -cp .:json-java.jar Test (Unix Systems)
+```
-Unit tests are maintained in a separate project. Contributing developers can test
-JSON-java pull requests with the code in this project:
-https://github.com/stleary/JSON-Java-unit-test
+*Expected output*
-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 7159: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc7159#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.
+```json
+{"abc":"def"}
+```
-Although 1.6 compatibility is currently supported, it is not a project goal and may be
-removed in some future release.
+
+**Tools to build the package and execute the unit tests**
-In compliance with RFC7159 page 10 section 9, the parser is more lax with what is valid
-JSON than the Generator. For Example, the tab character (U+0009) is allowed when reading
-JSON Text strings, but when output by the Generator, 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.
+Execute the test suite with Maven:
+```shell
+mvn clean test
+```
-Release history:
+Execute the test suite with Gradlew:
-~~~
-20180813 POM change to include Automatic-Module-Name (#431)
+```shell
+gradlew clean build test
+```
-20180130 Recent commits
+*Optional* Execute the test suite in strict mode with Gradlew:
-20171018 Checkpoint for recent commits.
+```shell
+gradlew testWithStrictMode
+```
-20170516 Roll up recent commits.
+*Optional* Execute the test suite in strict mode with Maven:
-20160810 Revert code that was breaking opt*() methods.
+```shell
+mvn test -P test-strict-mode
+```
-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
+# Notes
-20160212 Java 1.6 compatibility, OSGi bundle. Contains the latest code as of 12 Feb, 2016.
+For more information, please see [NOTES.md](https://github.com/stleary/JSON-java/blob/master/docs/NOTES.md)
-20151123 JSONObject and JSONArray initialization with generics. Contains the
-latest code as of 23 Nov, 2015.
+# Files
-20150729 Checkpoint for Maven central repository release. Contains the latest code
-as of 29 July, 2015.
-~~~
+For more information on files, please see [FILES.md](https://github.com/stleary/JSON-java/blob/master/docs/FILES.md)
+# 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
+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 100644
index 55362b274..000000000
--- a/XML.java
+++ /dev/null
@@ -1,683 +0,0 @@
-package org.json;
-
-/*
-Copyright (c) 2015 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.Reader;
-import java.io.StringReader;
-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 2016-08-10
- */
-@SuppressWarnings("boxing")
-public class XML {
- /** The Character '&'. */
- public static final Character AMP = '&';
-
- /** The Character '''. */
- public static final Character APOS = '\'';
-
- /** The Character '!'. */
- public static final Character BANG = '!';
-
- /** The Character '='. */
- public static final Character EQ = '=';
-
- /** The Character '>'. */
- public static final Character GT = '>';
-
- /** The Character '<'. */
- public static final Character LT = '<';
-
- /** The Character '?'. */
- public static final Character QUEST = '?';
-
- /** The Character '"'. */
- public static final Character QUOT = '"';
-
- /** The Character '/'. */
- public static final Character SLASH = '/';
-
- /**
- * Creates an iterator for navigating Code Points in a string instead of
- * characters. Once Java7 support is dropped, this can be replaced with
- *
- * string.codePoints()
- *
- * which is available in Java8 and above.
- *
- * @see http://stackoverflow.com/a/21791059/6030888
- */
- private static Iterable codePointIterator(final String string) {
- return new Iterable() {
- @Override
- public Iterator iterator() {
- return new Iterator() {
- private int nextIndex = 0;
- private int length = string.length();
-
- @Override
- public boolean hasNext() {
- return this.nextIndex < this.length;
- }
-
- @Override
- public Integer next() {
- int result = string.codePointAt(this.nextIndex);
- this.nextIndex += Character.charCount(result);
- return result;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
- };
- }
-
- /**
- * 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 "
- * ' (single quote / apostrophe) is replaced by '
- *
- *
- * @param string
- * The string to be escaped.
- * @return The escaped string.
- */
- public static String escape(String string) {
- StringBuilder sb = new StringBuilder(string.length());
- for (final int cp : codePointIterator(string)) {
- switch (cp) {
- case '&':
- sb.append("&");
- break;
- case '<':
- sb.append("<");
- break;
- case '>':
- sb.append(">");
- break;
- case '"':
- sb.append(""");
- break;
- case '\'':
- sb.append("'");
- break;
- default:
- if (mustEscape(cp)) {
- sb.append("");
- sb.append(Integer.toHexString(cp));
- sb.append(';');
- } else {
- sb.appendCodePoint(cp);
- }
- }
- }
- return sb.toString();
- }
-
- /**
- * @param cp code point to test
- * @return true if the code point is not valid for an XML
- */
- private static boolean mustEscape(int cp) {
- /* Valid range from https://www.w3.org/TR/REC-xml/#charsets
- *
- * #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
- *
- * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
- */
- // isISOControl is true when (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F)
- // all ISO control characters are out of range except tabs and new lines
- return (Character.isISOControl(cp)
- && cp != 0x9
- && cp != 0xA
- && cp != 0xD
- ) || !(
- // valid the range of acceptable characters that aren't control
- (cp >= 0x20 && cp <= 0xD7FF)
- || (cp >= 0xE000 && cp <= 0xFFFD)
- || (cp >= 0x10000 && cp <= 0x10FFFF)
- )
- ;
- }
-
- /**
- * Removes XML escapes from the string.
- *
- * @param string
- * string to remove escapes from
- * @return string with converted entities
- */
- public static String unescape(String string) {
- StringBuilder sb = new StringBuilder(string.length());
- for (int i = 0, length = string.length(); i < length; i++) {
- char c = string.charAt(i);
- if (c == '&') {
- final int semic = string.indexOf(';', i);
- if (semic > i) {
- final String entity = string.substring(i + 1, semic);
- sb.append(XMLTokener.unescapeEntity(entity));
- // skip past the entity we just parsed.
- i += entity.length() + 1;
- } else {
- // this shouldn't happen in most cases since the parser
- // errors on unclosed entries.
- sb.append(c);
- }
- } else {
- // not part of an entity
- sb.append(c);
- }
- }
- return sb.toString();
- }
-
- /**
- * Throw an exception if the string contains whitespace. Whitespace is not
- * allowed in tagNames and attributes.
- *
- * @param string
- * A string.
- * @throws JSONException Thrown if the string contains whitespace or is empty.
- */
- 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, boolean keepStrings)
- 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,
- keepStrings ? ((String)token) : stringToValue((String) token));
- token = null;
- } else {
- jsonobject.accumulate(string, "");
- }
-
-
- } else if (token == SLASH) {
- // Empty tag <.../>
- if (x.nextToken() != GT) {
- throw x.syntaxError("Misshaped tag");
- }
- if (jsonobject.length() > 0) {
- context.accumulate(tagName, jsonobject);
- } else {
- context.accumulate(tagName, "");
- }
- return false;
-
- } else if (token == GT) {
- // Content, between <...> and
- 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",
- keepStrings ? string : stringToValue(string));
- }
-
- } else if (token == LT) {
- // Nested element
- if (parse(x, jsonobject, tagName,keepStrings)) {
- 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");
- }
- }
- }
- }
-
- /**
- * This method is the same as {@link JSONObject#stringToValue(String)}.
- *
- * @param string String to convert
- * @return JSON value of this string or the string
- */
- // To maintain compatibility with the Android API, this method is a direct copy of
- // the one in JSONObject. Changes made here should be reflected there.
- public static Object stringToValue(String string) {
- 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 initial = string.charAt(0);
- if ((initial >= '0' && initial <= '9') || initial == '-') {
- try {
- // if we want full Big Number support this block can be replaced with:
- // return stringToNumber(string);
- if (string.indexOf('.') > -1 || string.indexOf('e') > -1
- || string.indexOf('E') > -1 || "-0".equals(string)) {
- Double d = Double.valueOf(string);
- if (!d.isInfinite() && !d.isNaN()) {
- return d;
- }
- } else {
- Long myLong = Long.valueOf(string);
- if (string.equals(myLong.toString())) {
- if (myLong.longValue() == myLong.intValue()) {
- return Integer.valueOf(myLong.intValue());
- }
- 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 Thrown if there is an errors while parsing the string
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- return toJSONObject(string, false);
- }
-
- /**
- * Convert a well-formed (but not necessarily valid) XML 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 reader The XML source reader.
- * @return A JSONObject containing the structured data from the XML string.
- * @throws JSONException Thrown if there is an errors while parsing the string
- */
- public static JSONObject toJSONObject(Reader reader) throws JSONException {
- return toJSONObject(reader, false);
- }
-
- /**
- * Convert a well-formed (but not necessarily valid) XML 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.
- *
- * All values are converted as strings, for 1, 01, 29.0 will not be coerced to
- * numbers but will instead be the exact value as seen in the XML document.
- *
- * @param reader The XML source reader.
- * @param keepStrings If true, then values will not be coerced into boolean
- * or numeric values and will instead be left as strings
- * @return A JSONObject containing the structured data from the XML string.
- * @throws JSONException Thrown if there is an errors while parsing the string
- */
- public static JSONObject toJSONObject(Reader reader, boolean keepStrings) throws JSONException {
- JSONObject jo = new JSONObject();
- XMLTokener x = new XMLTokener(reader);
- while (x.more()) {
- x.skipPast("<");
- if(x.more()) {
- parse(x, jo, null, keepStrings);
- }
- }
- return jo;
- }
-
- /**
- * 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.
- *
- * All values are converted as strings, for 1, 01, 29.0 will not be coerced to
- * numbers but will instead be the exact value as seen in the XML document.
- *
- * @param string
- * The source string.
- * @param keepStrings If true, then values will not be coerced into boolean
- * or numeric values and will instead be left as strings
- * @return A JSONObject containing the structured data from the XML string.
- * @throws JSONException Thrown if there is an errors while parsing the string
- */
- public static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException {
- return toJSONObject(new StringReader(string), keepStrings);
- }
-
- /**
- * Convert a JSONObject into a well-formed, element-normal XML string.
- *
- * @param object
- * A JSONObject.
- * @return A string.
- * @throws JSONException Thrown if there is an error parsing the string
- */
- 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 Thrown if there is an error parsing the string
- */
- public static String toString(final Object object, final String tagName)
- throws JSONException {
- StringBuilder sb = new StringBuilder();
- JSONArray ja;
- JSONObject jo;
- String string;
-
- if (object instanceof JSONObject) {
-
- // Emit
- if (tagName != null) {
- sb.append('<');
- sb.append(tagName);
- sb.append('>');
- }
-
- // Loop thru the keys.
- // don't use the new entrySet accessor to maintain Android Support
- jo = (JSONObject) object;
- for (final String key : jo.keySet()) {
- Object value = jo.opt(key);
- if (value == null) {
- value = "";
- } else if (value.getClass().isArray()) {
- value = new JSONArray(value);
- }
-
- // Emit content in body
- if ("content".equals(key)) {
- if (value instanceof JSONArray) {
- ja = (JSONArray) value;
- int jaLength = ja.length();
- // don't use the new iterator API to maintain support for Android
- for (int i = 0; i < jaLength; i++) {
- if (i > 0) {
- sb.append('\n');
- }
- Object val = ja.opt(i);
- sb.append(escape(val.toString()));
- }
- } else {
- sb.append(escape(value.toString()));
- }
-
- // Emit an array of similar keys
-
- } else if (value instanceof JSONArray) {
- ja = (JSONArray) value;
- int jaLength = ja.length();
- // don't use the new iterator API to maintain support for Android
- for (int i = 0; i < jaLength; i++) {
- Object val = ja.opt(i);
- if (val instanceof JSONArray) {
- sb.append('<');
- sb.append(key);
- sb.append('>');
- sb.append(toString(val));
- sb.append("");
- sb.append(key);
- sb.append('>');
- } else {
- sb.append(toString(val, 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();
-
- }
-
- if (object != null && (object instanceof JSONArray || object.getClass().isArray())) {
- if(object.getClass().isArray()) {
- ja = new JSONArray(object);
- } else {
- ja = (JSONArray) object;
- }
- int jaLength = ja.length();
- // don't use the new iterator API to maintain support for Android
- for (int i = 0; i < jaLength; i++) {
- Object val = ja.opt(i);
- // XML does not have good support for arrays. If an array
- // appears in a place where XML is lacking, synthesize an
- // element.
- sb.append(toString(val, tagName == null ? "array" : tagName));
- }
- return sb.toString();
- }
-
- 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..898f10dc7
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,139 @@
+/*
+ * This file was generated by the Gradle 'init' task.
+ */
+apply plugin: 'java'
+apply plugin: 'eclipse'
+apply plugin: 'jacoco'
+apply plugin: 'maven-publish'
+
+// for now, publishing to maven is still a manual process
+//plugins {
+ // id 'java'
+ //id 'maven-publish'
+// }
+
+repositories {
+ mavenLocal()
+ mavenCentral()
+ maven {
+ url = uri('https://oss.sonatype.org/content/repositories/snapshots')
+ }
+}
+
+// To view the report open build/reports/jacoco/test/html/index.html
+jacocoTestReport {
+ reports {
+ html.required = true
+ }
+}
+
+test {
+ finalizedBy jacocoTestReport
+}
+
+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 = 'v20251224-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..653e2bb8c
--- /dev/null
+++ b/docs/RELEASES.md
@@ -0,0 +1,64 @@
+# 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)
+
+~~~
+20251224 Records, fromJson(), and recent commits
+
+20250517 Strict mode hardening and recent commits
+
+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..8d0881cbe
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,254 @@
+
+ 4.0.0
+
+ org.json
+ json
+ 20251224
+ 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..f9afb8338
--- /dev/null
+++ b/src/main/java/org/json/CDL.java
@@ -0,0 +1,399 @@
+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.
+ * @deprecated (Utility class cannot be instantiated)
+ */
+ @Deprecated
+ 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.isEmpty() && (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..f7bab236f
--- /dev/null
+++ b/src/main/java/org/json/Cookie.java
@@ -0,0 +1,212 @@
+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.
+ * @deprecated (Utility class cannot be instantiated)
+ */
+ @Deprecated()
+ 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/CookieList.java b/src/main/java/org/json/CookieList.java
similarity index 62%
rename from CookieList.java
rename to src/main/java/org/json/CookieList.java
index c67ee3aea..ce47aee02 100644
--- a/CookieList.java
+++ b/src/main/java/org/json/CookieList.java
@@ -1,27 +1,7 @@
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.
*/
/**
@@ -31,6 +11,14 @@ of this software and associated documentation files (the "Software"), to deal
*/
public class CookieList {
+ /**
+ * Constructs a new CookieList object.
+ * @deprecated (Utility class cannot be instantiated)
+ */
+ @Deprecated
+ 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 '='.
@@ -42,7 +30,7 @@ public class CookieList {
* cookieJSONObject.getString("value"));
* @param string A cookie list string
* @return A JSONObject
- * @throws JSONException
+ * @throws JSONException if a called function fails
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
@@ -63,22 +51,22 @@ public static JSONObject toJSONObject(String string) throws JSONException {
* in the names and values are replaced by "%hh".
* @param jo A JSONObject
* @return A cookie list string
- * @throws JSONException
+ * @throws JSONException if a called function fails
*/
public static String toString(JSONObject jo) throws JSONException {
- boolean b = false;
+ 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 (b) {
+ if (isEndOfPair) {
sb.append(';');
}
sb.append(Cookie.escape(key));
sb.append("=");
sb.append(Cookie.escape(value.toString()));
- b = true;
+ isEndOfPair = true;
}
}
return sb.toString();
diff --git a/HTTP.java b/src/main/java/org/json/HTTP.java
similarity index 76%
rename from HTTP.java
rename to src/main/java/org/json/HTTP.java
index 70b88ee6c..44ab3a6d3 100644
--- a/HTTP.java
+++ b/src/main/java/org/json/HTTP.java
@@ -1,162 +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.Locale;
-
-/**
- * Convert an HTTP header to a JSONObject and back.
- * @author JSON.org
- * @version 2015-12-09
- */
-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(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();
- }
-}
+package org.json;
+
+/*
+Public Domain.
+*/
+
+import java.util.Locale;
+
+/**
+ * Convert an HTTP header to a JSONObject and back.
+ * @author JSON.org
+ * @version 2015-12-09
+ */
+public class HTTP {
+
+ /**
+ * Constructs a new HTTP object.
+ */
+ public 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 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
similarity index 53%
rename from HTTPTokener.java
rename to src/main/java/org/json/HTTPTokener.java
index 55f48ffa5..48cad31a3 100644
--- a/HTTPTokener.java
+++ b/src/main/java/org/json/HTTPTokener.java
@@ -1,27 +1,7 @@
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.
*/
/**
@@ -43,8 +23,8 @@ 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;
diff --git a/JSONArray.java b/src/main/java/org/json/JSONArray.java
similarity index 61%
rename from JSONArray.java
rename to src/main/java/org/json/JSONArray.java
index 537abb134..2a3c553a6 100644
--- a/JSONArray.java
+++ b/src/main/java/org/json/JSONArray.java
@@ -1,31 +1,10 @@
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.
*/
import java.io.IOException;
-import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.math.BigDecimal;
@@ -104,15 +83,30 @@ public JSONArray() {
* If there is a syntax error.
*/
public JSONArray(JSONTokener x) throws JSONException {
+ this(x, x.getJsonParserConfiguration());
+ }
+
+ /**
+ * Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration.
+ *
+ * @param x A JSONTokener instance from which the JSONArray is constructed.
+ * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
+ * @throws JSONException If a syntax error occurs during the construction of the JSONArray.
+ */
+ public JSONArray(JSONTokener x, JSONParserConfiguration jsonParserConfiguration) throws JSONException {
this();
+
+ boolean isInitial = x.getPrevious() == 0;
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['");
}
-
+
char nextChar = x.nextClean();
if (nextChar == 0) {
// array is unclosed. No ']' found, instead EOF
throw x.syntaxError("Expected a ',' or ']'");
+ } else if (nextChar==',' && jsonParserConfiguration.isStrictMode()) {
+ throw x.syntaxError("Array content starts with a ','");
}
if (nextChar != ']') {
x.back();
@@ -124,28 +118,59 @@ public JSONArray(JSONTokener x) throws JSONException {
x.back();
this.myArrayList.add(x.nextValue());
}
- switch (x.nextClean()) {
- case 0:
- // array is unclosed. No ']' found, instead EOF
- throw x.syntaxError("Expected a ',' or ']'");
- case ',':
- nextChar = x.nextClean();
- if (nextChar == 0) {
- // array is unclosed. No ']' found, instead EOF
- throw x.syntaxError("Expected a ',' or ']'");
- }
- if (nextChar == ']') {
- return;
- }
- x.back();
- break;
- case ']':
- return;
- default:
- throw x.syntaxError("Expected a ',' or ']'");
+ if (checkForSyntaxError(x, jsonParserConfiguration, isInitial)) return;
+ }
+ } else {
+ if (isInitial && jsonParserConfiguration.isStrictMode() && x.nextClean() != 0) {
+ throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text");
+ }
+ }
+ }
+
+ /** Convenience function. Checks for JSON syntax error.
+ * @param x A JSONTokener instance from which the JSONArray is constructed.
+ * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
+ * @param isInitial Boolean indicating position of char
+ * @return
+ */
+ private static boolean checkForSyntaxError(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) {
+ char nextChar;
+ switch (x.nextClean()) {
+ case 0:
+ // array is unclosed. No ']' found, instead EOF
+ throw x.syntaxError("Expected a ',' or ']'");
+ case ',':
+ nextChar = x.nextClean();
+ if (nextChar == 0) {
+ // array is unclosed. No ']' found, instead EOF
+ throw x.syntaxError("Expected a ',' or ']'");
+ }
+ if (nextChar == ']') {
+ // trailing commas are not allowed in strict mode
+ if (jsonParserConfiguration.isStrictMode()) {
+ throw x.syntaxError("Strict mode error: Expected another array element");
+ }
+ return true;
+ }
+ if (nextChar == ',') {
+ // consecutive commas are not allowed in strict mode
+ if (jsonParserConfiguration.isStrictMode()) {
+ throw x.syntaxError("Strict mode error: Expected a valid array element");
}
+ return true;
+ }
+ x.back();
+ break;
+ case ']':
+ if (isInitial && jsonParserConfiguration.isStrictMode() &&
+ x.nextClean() != 0) {
+ throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text");
}
+ return true;
+ default:
+ throw x.syntaxError("Expected a ',' or ']'");
}
+ return false;
}
/**
@@ -159,7 +184,22 @@ public JSONArray(JSONTokener x) throws JSONException {
* If there is a syntax error.
*/
public JSONArray(String source) throws JSONException {
- this(new JSONTokener(source));
+ this(source, new JSONParserConfiguration());
+ }
+
+ /**
+ * Construct a JSONArray from a source JSON text.
+ *
+ * @param source
+ * A string that begins with [ (left
+ * bracket) and ends with ]
+ * (right bracket).
+ * @param jsonParserConfiguration the parser config object
+ * @throws JSONException
+ * If there is a syntax error.
+ */
+ public JSONArray(String source, JSONParserConfiguration jsonParserConfiguration) throws JSONException {
+ this(new JSONTokener(source, jsonParserConfiguration), jsonParserConfiguration);
}
/**
@@ -169,13 +209,70 @@ public JSONArray(String source) throws JSONException {
* A Collection.
*/
public JSONArray(Collection> collection) {
+ this(collection, 0, new JSONParserConfiguration());
+ }
+
+ /**
+ * Construct a JSONArray from a Collection.
+ *
+ * @param collection
+ * A Collection.
+ * @param jsonParserConfiguration
+ * Configuration object for the JSON parser
+ */
+ public JSONArray(Collection> collection, JSONParserConfiguration jsonParserConfiguration) {
+ this(collection, 0, jsonParserConfiguration);
+ }
+
+ /**
+ * Construct a JSONArray from a collection with recursion depth.
+ *
+ * @param collection
+ * A Collection.
+ * @param recursionDepth
+ * Variable for tracking the count of nested object creations.
+ * @param jsonParserConfiguration
+ * Configuration object for the JSON parser
+ */
+ JSONArray(Collection> collection, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) {
+ if (recursionDepth > jsonParserConfiguration.getMaxNestingDepth()) {
+ throw new JSONException("JSONArray has reached recursion depth limit of " + jsonParserConfiguration.getMaxNestingDepth());
+ }
if (collection == null) {
this.myArrayList = new ArrayList