diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
new file mode 100644
index 0000000..98ee6c1
--- /dev/null
+++ b/.github/workflows/pipeline.yml
@@ -0,0 +1,74 @@
+# This workflow will build a Java project with Maven
+# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
+
+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:
+ runs-on: ubuntu-16.04
+ strategy:
+ matrix:
+ # build for java 1.6, however don't run any tests
+ java: [ 1.6 ]
+ name: Java ${{ matrix.java }}
+ steps:
+ - uses: actions/checkout@v2
+ - name: Setup java
+ uses: actions/setup-java@v1
+ with:
+ java-version: ${{ matrix.java }}
+ - name: Compile Java ${{ matrix.java }}
+ run: |
+ mkdir -p target/classes
+ javac -d target/classes/ src/main/java/org/json/*.java
+ - name: Create java ${{ matrix.java }} JAR
+ run: |
+ jar cvf target/org.json.jar -C target/classes .
+ - name: Upload Java ${{ matrix.java }} JAR
+ uses: actions/upload-artifact@v1
+ with:
+ name: Java ${{ matrix.java }} JAR
+ path: target/org.json.jar
+
+ build:
+ runs-on: ubuntu-16.04
+ strategy:
+ matrix:
+ # build against supported Java LTS versions:
+ java: [ 1.7, 8, 11 ]
+ name: Java ${{ matrix.java }}
+ steps:
+ - uses: actions/checkout@v2
+ - name: Setup java
+ uses: actions/setup-java@v1
+ with:
+ java-version: ${{ matrix.java }}
+ - name: Compile Java ${{ matrix.java }}
+ run: mvn clean compile -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} -Dmaven.test.skip=true -Dmaven.site.skip=true -Dmaven.javadoc.skip=true
+ - name: Run Tests ${{ matrix.java }}
+ run: |
+ mvn test -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }}
+ - name: Build Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ run: |
+ mvn surefire-report:report-only -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }}
+ mvn site -DgenerateReports=false -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }}
+ - name: Upload Test Results ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v1
+ with:
+ name: Test Results ${{ matrix.java }}
+ path: target/surefire-reports/
+ - name: Upload Test Report ${{ matrix.java }}
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v1
+ with:
+ name: Test Report ${{ matrix.java }}
+ path: target/site/
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 50b216e..7794c4c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,13 @@
# ignore Intellij Idea project files
.idea
*.iml
+/target/
+
+/bin/
+build
+.settings/
+/.gradle/
+/gradle/
+/gradlew
+/gradlew.bat
+.gitmodules
diff --git a/LICENSE b/LICENSE
index 02ee0ef..6cfb9b2 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,3 @@
-============================================================================
Copyright (c) 2002 JSON.org
@@ -21,3 +20,4 @@ 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 80930f8..8a58954 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@ JSON in Java [package org.json]
[](https://mvnrepository.com/artifact/org.json/json)
-**[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20190722/json-20190722.jar)**
+**[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20200518/json-20200518.jar)**
JSON is a light-weight, language independent, data interchange format.
See http://www.JSON.org/
@@ -22,6 +22,9 @@ package.
The package compiles on Java 1.6-1.8.
+# With 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. If you have difficulty using the new structure, please open an issue so we can work through it.
+
+
**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
@@ -84,9 +87,7 @@ cookie lists.
**XMLTokener.java**: `XMLTokener` extends `JSONTokener` for parsing XML text.
-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
+Unit tests are now included in the project, but require Java 1.8 at the present time. This will be fixed in a forthcoming commit.
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
@@ -148,3 +149,59 @@ as of 29 July, 2015.
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
+
+# Unit tests
+The test suite can be executed with Maven by running:
+```
+mvn test
+```
+The test suite can be executed with Gradle (6.4 or greater) by running:
+```
+gradle clean build 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 actually 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 prevents regressions and keeps 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 the it works as intended.
+
+
+**Caveats:**
+JSON-Java is Java 1.6-compatible, but JSON-Java-unit-tests requires Java 1.8. If you see this error when building JSON-Java-unit-test, make sure you have 1.8 installed, on your path, and set in JAVA_HOME:
+```
+Execution failed for task ':compileJava'.
+> invalid flag: -parameters
+```
+
+
+| Resource files used in test |
+| ------------- |
+| EnumTest.java |
+| MyBean.java |
+| MyBigNumberBean.java |
+| MyEnum.java |
+| MyEnumClass.java |
+| MyEnumField.java |
+| MyJsonString.java |
+| MyPublicClass.java |
+| PropertyTest.java |
+| JunitTestSuite.java |
+| StringsResourceBundle.java |
+| TestRunner.java |
+| Util.java |
+
+
+
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..64f87d2
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,58 @@
+/*
+ * This file was generated by the Gradle 'init' task.
+ */
+apply plugin: 'java'
+apply plugin: 'eclipse'
+// apply plugin: 'jacoco'
+apply plugin: 'maven-publish'
+
+//plugins {
+ // id 'java'
+ //id 'maven-publish'
+// }
+
+repositories {
+ mavenLocal()
+ maven {
+ url = uri('https://oss.sonatype.org/content/repositories/snapshots')
+ }
+
+ maven {
+ url = uri('http://repo.maven.apache.org/maven2')
+ }
+}
+
+dependencies {
+ testImplementation 'junit:junit:4.12'
+ testImplementation 'com.jayway.jsonpath:json-path:2.1.0'
+ testImplementation 'org.mockito:mockito-core:1.9.5'
+}
+
+subprojects {
+ tasks.withType(Javadoc).all { enabled = false }
+}
+
+group = 'org.json'
+version = 'v20200429-SNAPSHOT'
+description = 'JSON in Java'
+sourceCompatibility = '1.7'
+
+configurations.all {
+}
+
+java {
+ withSourcesJar()
+ withJavadocJar()
+}
+
+publishing {
+ publications {
+ maven(MavenPublication) {
+ from(components.java)
+ }
+ }
+}
+
+tasks.withType(JavaCompile) {
+ options.encoding = 'UTF-8'
+}
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..f3d88b1
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 0000000..a4b4429
--- /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 100644
index 0000000..2fe81a7
--- /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 0000000..9109989
--- /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/pom.xml b/pom.xml
new file mode 100644
index 0000000..1dde059
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,193 @@
+
{ - * Method: "POST" (for example), - * "Request-URI": "/" (for example), - * "HTTP-Version": "HTTP/1.1" (for example) - * }- * A response header will contain - *
{ - * "HTTP-Version": "HTTP/1.1" (for example), - * "Status-Code": "200" (for example), - * "Reason-Phrase": "OK" (for example) - * }- * In addition, the other parameters in the header will be captured, using - * the HTTP field names as JSON names, so that
- * Date: Sun, 26 May 2002 18:06:04 GMT - * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s - * Cache-Control: no-cache- * become - *
{... - * Date: "Sun, 26 May 2002 18:06:04 GMT", - * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", - * "Cache-Control": "no-cache", - * ...}- * 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 - *
{ - * Method: "POST" (for example), - * "Request-URI": "/" (for example), - * "HTTP-Version": "HTTP/1.1" (for example) - * }- * A response header must contain - *
{ - * "HTTP-Version": "HTTP/1.1" (for example), - * "Status-Code": "200" (for example), - * "Reason-Phrase": "OK" (for example) - * }- * 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; + +/* +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 + *
{ + * Method: "POST" (for example), + * "Request-URI": "/" (for example), + * "HTTP-Version": "HTTP/1.1" (for example) + * }+ * A response header will contain + *
{ + * "HTTP-Version": "HTTP/1.1" (for example), + * "Status-Code": "200" (for example), + * "Reason-Phrase": "OK" (for example) + * }+ * In addition, the other parameters in the header will be captured, using + * the HTTP field names as JSON names, so that
{@code + * Date: Sun, 26 May 2002 18:06:04 GMT + * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s + * Cache-Control: no-cache}+ * become + *
{@code + * Date: "Sun, 26 May 2002 18:06:04 GMT", + * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", + * "Cache-Control": "no-cache", + * ...}+ * 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 + *
{ + * Method: "POST" (for example), + * "Request-URI": "/" (for example), + * "HTTP-Version": "HTTP/1.1" (for example) + * }+ * A response header must contain + *
{ + * "HTTP-Version": "HTTP/1.1" (for example), + * "Status-Code": "200" (for example), + * "Reason-Phrase": "OK" (for example) + * }+ * 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 97% rename from HTTPTokener.java rename to src/main/java/org/json/HTTPTokener.java index 55f48ff..16c7081 100644 --- a/HTTPTokener.java +++ b/src/main/java/org/json/HTTPTokener.java @@ -43,8 +43,8 @@ public class HTTPTokener extends JSONTokener { /** * 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 94% rename from JSONArray.java rename to src/main/java/org/json/JSONArray.java index 8847c5d..3082974 100644 --- a/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -173,9 +173,7 @@ public class JSONArray implements Iterable