Compare commits

...

11 Commits

Author SHA1 Message Date
stleary
6daabb43ab update-copyright - Replace copyright and license restrictions with Public Domain 2022-08-23 20:00:25 -05:00
Sean Leary
57f785c42e Merge pull request #687 from schw1804/patch-1
Fix typo
2022-08-23 17:13:10 -05:00
Joshua Schwartz
3eecd67a3b Fix typo 2022-08-23 15:00:01 -05:00
Sean Leary
5a587bbdfd Merge pull request #685 from stleary/map-unit-tests
JSONObject map type unit tests
2022-08-23 07:59:35 -05:00
stleary
e0534b3ec7 initial attempt to test for inconsistent map types in JSONObject 2022-08-20 16:14:34 -05:00
Sean Leary
88ca19042b Merge pull request #684 from stleary/pipeline-fix-1
pipeline-fix-1 remove v7 build from pipeline
2022-08-20 08:33:23 -05:00
stleary
b4036e6a8e pipeline-fix-1 remove v7 build from pipeline 2022-08-13 12:50:10 -05:00
Sean Leary
6f92a3ab4e Merge pull request #675 from johnjaylward/Iss-649-better-error-message
Updates value error messages to be consistent.
2022-03-24 20:32:31 -05:00
John J. Aylward
beae279b21 Updates tests to have updated message expectations 2022-03-21 13:06:19 -04:00
John J. Aylward
a642329314 Updates value error messages to be consistent.
Provide both the type and value that failed conversion. Tries not to
"toString" large value types like Arrays or Maps. For those types it
will just output the type and not a value.
2022-03-21 12:48:25 -04:00
Sean Leary
9abb35ad39 Update RELEASES.md 2022-03-20 09:34:12 -05:00
45 changed files with 513 additions and 1077 deletions

View File

@@ -42,7 +42,7 @@ jobs:
strategy: strategy:
matrix: matrix:
# build against supported Java LTS versions: # build against supported Java LTS versions:
java: [ 1.7, 8, 11 ] java: [ 8, 11 ]
name: Java ${{ matrix.java }} name: Java ${{ matrix.java }}
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2

View File

@@ -218,7 +218,7 @@ import java.util.Properties;
} }
``` ```
<h2>Part 2: Conversion methods</h2> <h2>Part 2: Conversion methods</h2>
<p>We don't need to have a JSON docuemnt to work. This project also admits conversions from other type of files.</p> <p>We don't need to have a JSON document to work. This project also admits conversions from other type of files.</p>
<p>Secondly, we can also convert from JSON to those type of files.</p> <p>Secondly, we can also convert from JSON to those type of files.</p>
<h3>Extra: Conversion to JSONArray</h3> <h3>Extra: Conversion to JSONArray</h3>

23
LICENSE
View File

@@ -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.

View File

@@ -28,8 +28,6 @@ Project goals include:
The files in this package implement JSON encoders and decoders. The package can also convert between JSON and XML, HTTP headers, Cookies, and CDL. The files in this package implement JSON encoders and decoders. The package can also convert between JSON and XML, HTTP headers, Cookies, and CDL.
The license includes this restriction: ["The software shall be used for good, not evil."](https://en.wikipedia.org/wiki/Douglas_Crockford#%22Good,_not_Evil%22) If your conscience cannot live with that, then choose a different package.
# If you would like to contribute to this project # If you would like to contribute to this project
For more information on contributions, please see [CONTRIBUTING.md](https://github.com/stleary/JSON-java/blob/master/docs/CONTRIBUTING.md) For more information on contributions, please see [CONTRIBUTING.md](https://github.com/stleary/JSON-java/blob/master/docs/CONTRIBUTING.md)

View File

@@ -5,7 +5,7 @@ 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) [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)
~~~ ~~~
20220320 Recent commits 20220320 Wrap StackOverflow with JSONException
20211205 Recent commits and some bug fixes for similar() 20211205 Recent commits and some bug fixes for similar()

27
pom.xml
View File

@@ -18,10 +18,6 @@
This is a reference implementation. There is a large number of JSON packages 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 in Java. Perhaps someday the Java community will standardize on one. Until
then, choose carefully. 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.
</description> </description>
<url>https://github.com/douglascrockford/JSON-java</url> <url>https://github.com/douglascrockford/JSON-java</url>
@@ -39,28 +35,9 @@
<licenses> <licenses>
<license> <license>
<name>The JSON License</name> <name>Public Domain</name>
<url>http://json.org/license.html</url> <url>https://github.com/stleary/JSON-java/blob/master/LICENSE</url>
<distribution>repo</distribution> <distribution>repo</distribution>
<comments>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.
</comments>
</license> </license>
</licenses> </licenses>

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -3,27 +3,7 @@ package org.json;
import java.util.Locale; import java.util.Locale;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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; import java.util.Locale;

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/ */
import java.io.IOException; import java.io.IOException;
@@ -288,7 +268,7 @@ public class JSONArray implements Iterable<Object> {
.equalsIgnoreCase("true"))) { .equalsIgnoreCase("true"))) {
return true; return true;
} }
throw wrongValueFormatException(index, "boolean", null); throw wrongValueFormatException(index, "boolean", object, null);
} }
/** /**
@@ -309,7 +289,7 @@ public class JSONArray implements Iterable<Object> {
try { try {
return Double.parseDouble(object.toString()); return Double.parseDouble(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(index, "double", e); throw wrongValueFormatException(index, "double", object, e);
} }
} }
@@ -331,7 +311,7 @@ public class JSONArray implements Iterable<Object> {
try { try {
return Float.parseFloat(object.toString()); return Float.parseFloat(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(index, "float", e); throw wrongValueFormatException(index, "float", object, e);
} }
} }
@@ -353,7 +333,7 @@ public class JSONArray implements Iterable<Object> {
} }
return JSONObject.stringToNumber(object.toString()); return JSONObject.stringToNumber(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(index, "number", e); throw wrongValueFormatException(index, "number", object, e);
} }
} }
@@ -378,7 +358,7 @@ public class JSONArray implements Iterable<Object> {
// If it did, I would re-implement this with the Enum.valueOf // If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException // method and place any thrown exception in the JSONException
throw wrongValueFormatException(index, "enum of type " throw wrongValueFormatException(index, "enum of type "
+ JSONObject.quote(clazz.getSimpleName()), null); + JSONObject.quote(clazz.getSimpleName()), opt(index), null);
} }
return val; return val;
} }
@@ -441,7 +421,7 @@ public class JSONArray implements Iterable<Object> {
try { try {
return Integer.parseInt(object.toString()); return Integer.parseInt(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(index, "int", e); throw wrongValueFormatException(index, "int", object, e);
} }
} }
@@ -460,7 +440,7 @@ public class JSONArray implements Iterable<Object> {
if (object instanceof JSONArray) { if (object instanceof JSONArray) {
return (JSONArray) object; return (JSONArray) object;
} }
throw wrongValueFormatException(index, "JSONArray", null); throw wrongValueFormatException(index, "JSONArray", object, null);
} }
/** /**
@@ -478,7 +458,7 @@ public class JSONArray implements Iterable<Object> {
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
return (JSONObject) object; return (JSONObject) object;
} }
throw wrongValueFormatException(index, "JSONObject", null); throw wrongValueFormatException(index, "JSONObject", object, null);
} }
/** /**
@@ -499,7 +479,7 @@ public class JSONArray implements Iterable<Object> {
try { try {
return Long.parseLong(object.toString()); return Long.parseLong(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(index, "long", e); throw wrongValueFormatException(index, "long", object, e);
} }
} }
@@ -517,7 +497,7 @@ public class JSONArray implements Iterable<Object> {
if (object instanceof String) { if (object instanceof String) {
return (String) object; return (String) object;
} }
throw wrongValueFormatException(index, "String", null); throw wrongValueFormatException(index, "String", object, null);
} }
/** /**
@@ -1464,6 +1444,7 @@ public class JSONArray implements Iterable<Object> {
* &nbsp;<small>(right bracket)</small>. * &nbsp;<small>(right bracket)</small>.
* @throws JSONException if a called function fails * @throws JSONException if a called function fails
*/ */
@SuppressWarnings("resource")
public String toString(int indentFactor) throws JSONException { public String toString(int indentFactor) throws JSONException {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) { synchronized (sw.getBuffer()) {
@@ -1513,6 +1494,7 @@ public class JSONArray implements Iterable<Object> {
* @return The writer. * @return The writer.
* @throws JSONException if a called function fails or unable to write * @throws JSONException if a called function fails or unable to write
*/ */
@SuppressWarnings("resource")
public Writer write(Writer writer, int indentFactor, int indent) public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException { throws JSONException {
try { try {
@@ -1680,22 +1662,6 @@ public class JSONArray implements Iterable<Object> {
} }
} }
/**
* Create a new JSONException in a common format for incorrect conversions.
* @param idx index of the item
* @param valueType the type of value being coerced to
* @param cause optional cause of the coercion failure
* @return JSONException that can be thrown.
*/
private static JSONException wrongValueFormatException(
int idx,
String valueType,
Throwable cause) {
return new JSONException(
"JSONArray[" + idx + "] is not a " + valueType + "."
, cause);
}
/** /**
* Create a new JSONException in a common format for incorrect conversions. * Create a new JSONException in a common format for incorrect conversions.
* @param idx index of the item * @param idx index of the item
@@ -1708,8 +1674,19 @@ public class JSONArray implements Iterable<Object> {
String valueType, String valueType,
Object value, Object value,
Throwable cause) { Throwable cause) {
if(value == null) {
return new JSONException( return new JSONException(
"JSONArray[" + idx + "] is not a " + valueType + " (" + value + ")." "JSONArray[" + idx + "] is not a " + valueType + " (null)."
, cause);
}
// don't try to toString collections or known object types that could be large.
if(value instanceof Map || value instanceof Iterable || value instanceof JSONObject) {
return new JSONException(
"JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + ")."
, cause);
}
return new JSONException(
"JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")."
, cause); , cause);
} }

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2008 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,31 +1,10 @@
package org.json; package org.json;
import java.io.Closeable;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
*/
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.Closeable;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.io.Writer; import java.io.Writer;
@@ -166,6 +145,10 @@ public class JSONObject {
*/ */
private final Map<String, Object> map; private final Map<String, Object> map;
public Class<? extends Map> getMapType() {
return map.getClass();
}
/** /**
* It is sometimes more convenient and less ambiguous to have a * It is sometimes more convenient and less ambiguous to have a
* <code>NULL</code> object than to use Java's <code>null</code> value. * <code>NULL</code> object than to use Java's <code>null</code> value.
@@ -609,7 +592,7 @@ public class JSONObject {
// JSONException should really take a throwable argument. // JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf // If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException // method and place any thrown exception in the JSONException
throw wrongValueFormatException(key, "enum of type " + quote(clazz.getSimpleName()), null); throw wrongValueFormatException(key, "enum of type " + quote(clazz.getSimpleName()), opt(key), null);
} }
return val; return val;
} }
@@ -635,7 +618,7 @@ public class JSONObject {
.equalsIgnoreCase("true"))) { .equalsIgnoreCase("true"))) {
return true; return true;
} }
throw wrongValueFormatException(key, "Boolean", null); throw wrongValueFormatException(key, "Boolean", object, null);
} }
/** /**
@@ -697,7 +680,7 @@ public class JSONObject {
try { try {
return Double.parseDouble(object.toString()); return Double.parseDouble(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(key, "double", e); throw wrongValueFormatException(key, "double", object, e);
} }
} }
@@ -719,7 +702,7 @@ public class JSONObject {
try { try {
return Float.parseFloat(object.toString()); return Float.parseFloat(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(key, "float", e); throw wrongValueFormatException(key, "float", object, e);
} }
} }
@@ -741,7 +724,7 @@ public class JSONObject {
} }
return stringToNumber(object.toString()); return stringToNumber(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(key, "number", e); throw wrongValueFormatException(key, "number", object, e);
} }
} }
@@ -763,7 +746,7 @@ public class JSONObject {
try { try {
return Integer.parseInt(object.toString()); return Integer.parseInt(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(key, "int", e); throw wrongValueFormatException(key, "int", object, e);
} }
} }
@@ -781,7 +764,7 @@ public class JSONObject {
if (object instanceof JSONArray) { if (object instanceof JSONArray) {
return (JSONArray) object; return (JSONArray) object;
} }
throw wrongValueFormatException(key, "JSONArray", null); throw wrongValueFormatException(key, "JSONArray", object, null);
} }
/** /**
@@ -798,7 +781,7 @@ public class JSONObject {
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
return (JSONObject) object; return (JSONObject) object;
} }
throw wrongValueFormatException(key, "JSONObject", null); throw wrongValueFormatException(key, "JSONObject", object, null);
} }
/** /**
@@ -819,7 +802,7 @@ public class JSONObject {
try { try {
return Long.parseLong(object.toString()); return Long.parseLong(object.toString());
} catch (Exception e) { } catch (Exception e) {
throw wrongValueFormatException(key, "long", e); throw wrongValueFormatException(key, "long", object, e);
} }
} }
@@ -875,7 +858,7 @@ public class JSONObject {
if (object instanceof String) { if (object instanceof String) {
return (String) object; return (String) object;
} }
throw wrongValueFormatException(key, "string", null); throw wrongValueFormatException(key, "string", object, null);
} }
/** /**
@@ -1201,13 +1184,12 @@ public class JSONObject {
} }
if (exact) { if (exact) {
return new BigDecimal(((Number)val).doubleValue()); return new BigDecimal(((Number)val).doubleValue());
}else { }
// use the string constructor so that we maintain "nice" values for doubles and floats // use the string constructor so that we maintain "nice" values for doubles and floats
// the double constructor will translate doubles to "exact" values instead of the likely // the double constructor will translate doubles to "exact" values instead of the likely
// intended representation // intended representation
return new BigDecimal(val.toString()); return new BigDecimal(val.toString());
} }
}
if (val instanceof Long || val instanceof Integer if (val instanceof Long || val instanceof Integer
|| val instanceof Short || val instanceof Byte){ || val instanceof Short || val instanceof Byte){
return new BigDecimal(((Number) val).longValue()); return new BigDecimal(((Number) val).longValue());
@@ -2021,6 +2003,7 @@ public class JSONObject {
* A String * A String
* @return A String correctly formatted for insertion in a JSON text. * @return A String correctly formatted for insertion in a JSON text.
*/ */
@SuppressWarnings("resource")
public static String quote(String string) { public static String quote(String string) {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) { synchronized (sw.getBuffer()) {
@@ -2141,7 +2124,7 @@ public class JSONObject {
} else if (valueThis instanceof Number && valueOther instanceof Number) { } else if (valueThis instanceof Number && valueOther instanceof Number) {
if (!isNumberSimilar((Number)valueThis, (Number)valueOther)) { if (!isNumberSimilar((Number)valueThis, (Number)valueOther)) {
return false; return false;
}; }
} else if (!valueThis.equals(valueOther)) { } else if (!valueThis.equals(valueOther)) {
return false; return false;
} }
@@ -2409,6 +2392,7 @@ public class JSONObject {
* @throws JSONException * @throws JSONException
* If the object contains an invalid number. * If the object contains an invalid number.
*/ */
@SuppressWarnings("resource")
public String toString(int indentFactor) throws JSONException { public String toString(int indentFactor) throws JSONException {
StringWriter w = new StringWriter(); StringWriter w = new StringWriter();
synchronized (w.getBuffer()) { synchronized (w.getBuffer()) {
@@ -2502,10 +2486,8 @@ public class JSONObject {
if (objectsRecord != null) { if (objectsRecord != null) {
return new JSONObject(object, objectsRecord); return new JSONObject(object, objectsRecord);
} }
else {
return new JSONObject(object); return new JSONObject(object);
} }
}
catch (JSONException exception) { catch (JSONException exception) {
throw exception; throw exception;
} catch (Exception exception) { } catch (Exception exception) {
@@ -2527,6 +2509,7 @@ public class JSONObject {
return this.write(writer, 0, 0); return this.write(writer, 0, 0);
} }
@SuppressWarnings("resource")
static final Writer writeValue(Writer writer, Object value, static final Writer writeValue(Writer writer, Object value,
int indentFactor, int indent) throws JSONException, IOException { int indentFactor, int indent) throws JSONException, IOException {
if (value == null || value.equals(null)) { if (value == null || value.equals(null)) {
@@ -2604,6 +2587,7 @@ public class JSONObject {
* @throws JSONException if a called function has an error or a write error * @throws JSONException if a called function has an error or a write error
* occurs * occurs
*/ */
@SuppressWarnings("resource")
public Writer write(Writer writer, int indentFactor, int indent) public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException { throws JSONException {
try { try {
@@ -2686,22 +2670,6 @@ public class JSONObject {
return results; return results;
} }
/**
* Create a new JSONException in a common format for incorrect conversions.
* @param key name of the key
* @param valueType the type of value being coerced to
* @param cause optional cause of the coercion failure
* @return JSONException that can be thrown.
*/
private static JSONException wrongValueFormatException(
String key,
String valueType,
Throwable cause) {
return new JSONException(
"JSONObject[" + quote(key) + "] is not a " + valueType + "."
, cause);
}
/** /**
* Create a new JSONException in a common format for incorrect conversions. * Create a new JSONException in a common format for incorrect conversions.
* @param key name of the key * @param key name of the key
@@ -2714,8 +2682,20 @@ public class JSONObject {
String valueType, String valueType,
Object value, Object value,
Throwable cause) { Throwable cause) {
if(value == null) {
return new JSONException( return new JSONException(
"JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value + ")." "JSONObject[" + quote(key) + "] is not a " + valueType + " (null)."
, cause);
}
// don't try to toString collections or known object types that could be large.
if(value instanceof Map || value instanceof Iterable || value instanceof JSONObject) {
return new JSONException(
"JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + ")."
, cause);
}
return new JSONException(
"JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")."
, cause); , cause);
} }

View File

@@ -10,27 +10,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2018 JSON.org Public Domain.
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.ElementType.METHOD;

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2018 JSON.org Public Domain.
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.ElementType.METHOD;

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2006 JSON.org Public Domain.
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.StringWriter; import java.io.StringWriter;

View File

@@ -8,27 +8,7 @@ import java.io.Reader;
import java.io.StringReader; import java.io.StringReader;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -5,27 +5,7 @@ import java.util.Collection;
import java.util.Map; import java.util.Map;
/* /*
Copyright (c) 2006 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.Enumeration; import java.util.Enumeration;

View File

@@ -1,32 +1,11 @@
package org.json; package org.json;
/* /*
Copyright (c) 2015 JSON.org Public Domain.
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.Reader;
import java.io.StringReader; import java.io.StringReader;
import java.lang.reflect.Method;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.Iterator; import java.util.Iterator;

View File

@@ -1,26 +1,6 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.Collections; import java.util.Collections;

View File

@@ -1,27 +1,7 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.Reader;

View File

@@ -1,26 +1,6 @@
package org.json; package org.json;
/* /*
Copyright (c) 2002 JSON.org Public Domain.
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.
*/ */
/** /**

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -237,6 +217,10 @@ public class JSONArrayTest {
assertTrue( assertTrue(
"The RAW Collection should give me the same as the Typed Collection", "The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObj)); expected.similar(jaObj));
Util.checkJSONArrayMaps(expected);
Util.checkJSONArrayMaps(jaObj);
Util.checkJSONArrayMaps(jaRaw);
Util.checkJSONArrayMaps(jaInt);
} }
/** /**
@@ -275,6 +259,7 @@ public class JSONArrayTest {
myList.get(i), myList.get(i),
jsonArray.getString(myInts.length + i)); jsonArray.getString(myInts.length + i));
} }
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -308,6 +293,9 @@ public class JSONArrayTest {
assertTrue( assertTrue(
"The RAW Collection should give me the same as the Typed Collection", "The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaInt)); expected.similar(jaInt));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jaRaw, jaObj, jaInt
)));
} }
@@ -351,6 +339,9 @@ public class JSONArrayTest {
assertTrue( assertTrue(
"The RAW Collection should give me the same as the Typed Collection", "The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj)); expected.similar(jaObjObj));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
expected, jaRaw, jaStrObj, jaStrInt, jaObjObj
)));
} }
/** /**
@@ -397,6 +388,7 @@ public class JSONArrayTest {
new Long(-1).equals(jsonArray.getLong(12))); new Long(-1).equals(jsonArray.getLong(12)));
assertTrue("Array value null", jsonArray.isNull(-1)); assertTrue("Array value null", jsonArray.isNull(-1));
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -412,7 +404,7 @@ public class JSONArrayTest {
assertTrue("expected getBoolean to fail", false); assertTrue("expected getBoolean to fail", false);
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expected an exception message", assertEquals("Expected an exception message",
"JSONArray[4] is not a boolean.",e.getMessage()); "JSONArray[4] is not a boolean (class java.lang.String : hello).",e.getMessage());
} }
try { try {
jsonArray.get(-1); jsonArray.get(-1);
@@ -426,43 +418,44 @@ public class JSONArrayTest {
assertTrue("expected getDouble to fail", false); assertTrue("expected getDouble to fail", false);
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expected an exception message", assertEquals("Expected an exception message",
"JSONArray[4] is not a double.",e.getMessage()); "JSONArray[4] is not a double (class java.lang.String : hello).",e.getMessage());
} }
try { try {
jsonArray.getInt(4); jsonArray.getInt(4);
assertTrue("expected getInt to fail", false); assertTrue("expected getInt to fail", false);
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expected an exception message", assertEquals("Expected an exception message",
"JSONArray[4] is not a int.",e.getMessage()); "JSONArray[4] is not a int (class java.lang.String : hello).",e.getMessage());
} }
try { try {
jsonArray.getJSONArray(4); jsonArray.getJSONArray(4);
assertTrue("expected getJSONArray to fail", false); assertTrue("expected getJSONArray to fail", false);
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expected an exception message", assertEquals("Expected an exception message",
"JSONArray[4] is not a JSONArray.",e.getMessage()); "JSONArray[4] is not a JSONArray (class java.lang.String : hello).",e.getMessage());
} }
try { try {
jsonArray.getJSONObject(4); jsonArray.getJSONObject(4);
assertTrue("expected getJSONObject to fail", false); assertTrue("expected getJSONObject to fail", false);
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expected an exception message", assertEquals("Expected an exception message",
"JSONArray[4] is not a JSONObject.",e.getMessage()); "JSONArray[4] is not a JSONObject (class java.lang.String : hello).",e.getMessage());
} }
try { try {
jsonArray.getLong(4); jsonArray.getLong(4);
assertTrue("expected getLong to fail", false); assertTrue("expected getLong to fail", false);
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expected an exception message", assertEquals("Expected an exception message",
"JSONArray[4] is not a long.",e.getMessage()); "JSONArray[4] is not a long (class java.lang.String : hello).",e.getMessage());
} }
try { try {
jsonArray.getString(5); jsonArray.getString(5);
assertTrue("expected getString to fail", false); assertTrue("expected getString to fail", false);
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expected an exception message", assertEquals("Expected an exception message",
"JSONArray[5] is not a String.",e.getMessage()); "JSONArray[5] is not a String (class java.math.BigDecimal : 0.002345).",e.getMessage());
} }
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -499,6 +492,7 @@ public class JSONArrayTest {
assertTrue("expected value4", "value4".equals(jsonArray.query("/10/key4"))); assertTrue("expected value4", "value4".equals(jsonArray.query("/10/key4")));
assertTrue("expected 0", Integer.valueOf(0).equals(jsonArray.query("/11"))); assertTrue("expected 0", Integer.valueOf(0).equals(jsonArray.query("/11")));
assertTrue("expected \"-1\"", "-1".equals(jsonArray.query("/12"))); assertTrue("expected \"-1\"", "-1".equals(jsonArray.query("/12")));
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -512,6 +506,9 @@ public class JSONArrayTest {
assertTrue("expected JSONArray length 13. instead found "+jsonArray.length(), jsonArray.length() == 13); assertTrue("expected JSONArray length 13. instead found "+jsonArray.length(), jsonArray.length() == 13);
JSONArray nestedJsonArray = jsonArray.getJSONArray(9); JSONArray nestedJsonArray = jsonArray.getJSONArray(9);
assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1); assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1);
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jsonArray, nestedJsonArray
)));
} }
/** /**
@@ -587,6 +584,10 @@ public class JSONArrayTest {
"hello".equals(jsonArray.optString(4))); "hello".equals(jsonArray.optString(4)));
assertTrue("Array opt string default implicit", assertTrue("Array opt string default implicit",
"".equals(jsonArray.optString(-1))); "".equals(jsonArray.optString(-1)));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jsonArray, nestedJsonArray
)));
Util.checkJSONObjectMaps(nestedJsonObject);
} }
/** /**
@@ -601,7 +602,9 @@ public class JSONArrayTest {
assertTrue("unexpected optLong value",ja.optLong(0,0)==123); assertTrue("unexpected optLong value",ja.optLong(0,0)==123);
assertTrue("unexpected optDouble value",ja.optDouble(0,0.0)==123.0); assertTrue("unexpected optDouble value",ja.optDouble(0,0.0)==123.0);
assertTrue("unexpected optBigInteger value",ja.optBigInteger(0,BigInteger.ZERO).compareTo(new BigInteger("123"))==0); assertTrue("unexpected optBigInteger value",ja.optBigInteger(0,BigInteger.ZERO).compareTo(new BigInteger("123"))==0);
assertTrue("unexpected optBigDecimal value",ja.optBigDecimal(0,BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); } assertTrue("unexpected optBigDecimal value",ja.optBigDecimal(0,BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0);
Util.checkJSONArrayMaps(ja);
}
/** /**
* Exercise the JSONArray.put(value) method with various parameters * Exercise the JSONArray.put(value) method with various parameters
@@ -677,6 +680,8 @@ public class JSONArrayTest {
assertTrue("expected 2 items in [9]", ((List<?>)(JsonPath.read(doc, "$[9]"))).size() == 2); assertTrue("expected 2 items in [9]", ((List<?>)(JsonPath.read(doc, "$[9]"))).size() == 2);
assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/9/0"))); assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/9/0")));
assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/9/1"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/9/1")));
Util.checkJSONArrayMaps(jsonArray);
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -756,6 +761,8 @@ public class JSONArrayTest {
assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/9/1"))); assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/9/1")));
assertTrue("expected 1 item in [10]", ((Map<?,?>)(JsonPath.read(doc, "$[10]"))).size() == 1); assertTrue("expected 1 item in [10]", ((Map<?,?>)(JsonPath.read(doc, "$[10]"))).size() == 1);
assertTrue("expected v1", "v1".equals(jsonArray.query("/10/k1"))); assertTrue("expected v1", "v1".equals(jsonArray.query("/10/k1")));
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -772,6 +779,7 @@ public class JSONArrayTest {
jsonArray.remove(0); jsonArray.remove(0);
assertTrue("array should be empty", null == jsonArray.remove(5)); assertTrue("array should be empty", null == jsonArray.remove(5));
assertTrue("jsonArray should be empty", jsonArray.isEmpty()); assertTrue("jsonArray should be empty", jsonArray.isEmpty());
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -811,6 +819,12 @@ public class JSONArrayTest {
otherJsonArray.put("world"); otherJsonArray.put("world");
assertTrue("arrays values differ", assertTrue("arrays values differ",
!jsonArray.similar(otherJsonArray)); !jsonArray.similar(otherJsonArray));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jsonArray, otherJsonArray
)));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, otherJsonObject
)));
} }
/** /**
@@ -894,6 +908,7 @@ public class JSONArrayTest {
for (String s : jsonArray4Strs) { for (String s : jsonArray4Strs) {
list.contains(s); list.contains(s);
} }
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -905,6 +920,9 @@ public class JSONArrayTest {
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
assertTrue("toJSONObject should return null", assertTrue("toJSONObject should return null",
null == jsonArray.toJSONObject(names)); null == jsonArray.toJSONObject(names));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
names, jsonArray
)));
} }
/** /**
@@ -926,6 +944,7 @@ public class JSONArrayTest {
assertTrue("expected 5", Integer.valueOf(5).equals(jsonArray.query("/4"))); assertTrue("expected 5", Integer.valueOf(5).equals(jsonArray.query("/4")));
assertTrue("expected 6", Integer.valueOf(6).equals(jsonArray.query("/5"))); assertTrue("expected 6", Integer.valueOf(6).equals(jsonArray.query("/5")));
assertTrue("expected 7", Integer.valueOf(7).equals(jsonArray.query("/6"))); assertTrue("expected 7", Integer.valueOf(7).equals(jsonArray.query("/6")));
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -968,6 +987,10 @@ public class JSONArrayTest {
assertTrue("Array value string long", assertTrue("Array value string long",
new Long(-1).equals(Long.parseLong((String) it.next()))); new Long(-1).equals(Long.parseLong((String) it.next())));
assertTrue("should be at end of array", !it.hasNext()); assertTrue("should be at end of array", !it.hasNext());
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jsonArray, nestedJsonArray
)));
Util.checkJSONObjectMaps(nestedJsonObject);
} }
@Test(expected = JSONPointerException.class) @Test(expected = JSONPointerException.class)
@@ -1010,6 +1033,7 @@ public class JSONArrayTest {
} finally { } finally {
stringWriter.close(); stringWriter.close();
} }
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -1069,9 +1093,11 @@ public class JSONArrayTest {
&& actualStr.contains("\"key2\": false") && actualStr.contains("\"key2\": false")
&& actualStr.contains("\"key3\": 3.14") && actualStr.contains("\"key3\": 3.14")
); );
Util.checkJSONArrayMaps(finalArray);
} finally { } finally {
stringWriter.close(); stringWriter.close();
} }
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -1182,6 +1208,7 @@ public class JSONArrayTest {
// assert that the new list is mutable // assert that the new list is mutable
assertTrue("Removing an entry should succeed", list.remove(2) != null); assertTrue("Removing an entry should succeed", list.remove(2) != null);
assertTrue("List should have 2 elements", list.size() == 2); assertTrue("List should have 2 elements", list.size() == 2);
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -1194,7 +1221,7 @@ public class JSONArrayTest {
assertNotNull(new JSONArray(5)); assertNotNull(new JSONArray(5));
// Check Size -> Even though the capacity of the JSONArray can be specified using a positive // Check Size -> Even though the capacity of the JSONArray can be specified using a positive
// integer but the length of JSONArray always reflects upon the items added into it. // integer but the length of JSONArray always reflects upon the items added into it.
assertEquals(0l, new JSONArray(10).length()); // assertEquals(0l, new JSONArray(10).length());
try { try {
assertNotNull("Should throw an exception", new JSONArray(-1)); assertNotNull("Should throw an exception", new JSONArray(-1));
} catch (JSONException e) { } catch (JSONException e) {
@@ -1223,8 +1250,8 @@ public class JSONArrayTest {
((Collection<Object>)o).add("test"); ((Collection<Object>)o).add("test");
((Collection<Object>)o).add(false); ((Collection<Object>)o).add(false);
try { try {
a = new JSONArray(o); JSONArray a0 = new JSONArray(o);
assertNull("Should error", a); assertNull("Should error", a0);
} catch (JSONException ex) { } catch (JSONException ex) {
} }
@@ -1232,10 +1259,11 @@ public class JSONArrayTest {
// this is required for backwards compatibility // this is required for backwards compatibility
o = a; o = a;
try { try {
a = new JSONArray(o); JSONArray a1 = new JSONArray(o);
assertNull("Should error", a); assertNull("Should error", a1);
} catch (JSONException ex) { } catch (JSONException ex) {
} }
Util.checkJSONArrayMaps(a);
} }
/** /**
@@ -1252,6 +1280,9 @@ public class JSONArrayTest {
for(int i = 0; i < a1.length(); i++) { for(int i = 0; i < a1.length(); i++) {
assertEquals("index " + i + " are equal", a1.get(i), a2.get(i)); assertEquals("index " + i + " are equal", a1.get(i), a2.get(i));
} }
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
a1, a2
)));
} }
/** /**
@@ -1269,6 +1300,9 @@ public class JSONArrayTest {
for(int i = 0; i < a1.length(); i++) { for(int i = 0; i < a1.length(); i++) {
assertEquals("index " + i + " are equal", a1.get(i), a2.get(i)); assertEquals("index " + i + " are equal", a1.get(i), a2.get(i));
} }
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
a1, a2
)));
} }
/** /**
@@ -1284,6 +1318,7 @@ public class JSONArrayTest {
jsonArray.clear(); //Clears the JSONArray jsonArray.clear(); //Clears the JSONArray
assertTrue("expected jsonArray.length() == 0", jsonArray.length() == 0); //Check if its length is 0 assertTrue("expected jsonArray.length() == 0", jsonArray.length() == 0); //Check if its length is 0
jsonArray.getInt(0); //Should throws org.json.JSONException: JSONArray[0] not found jsonArray.getInt(0); //Should throws org.json.JSONException: JSONArray[0] not found
Util.checkJSONArrayMaps(jsonArray);
} }
/** /**
@@ -1297,5 +1332,6 @@ public class JSONArrayTest {
JSONArray json_input = new JSONArray(tokener); JSONArray json_input = new JSONArray(tokener);
assertNotNull(json_input); assertNotNull(json_input);
fail("Excepected Exception."); fail("Excepected Exception.");
Util.checkJSONArrayMaps(json_input);
} }
} }

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;
@@ -158,7 +138,7 @@ public class JSONMLTest {
assertTrue("Expecting an exception", false); assertTrue("Expecting an exception", false);
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONArray[0] is not a String.", "JSONArray[0] is not a String (class org.json.JSONArray).",
e.getMessage()); e.getMessage());
} }
} }

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -41,14 +21,7 @@ import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -80,6 +53,7 @@ import org.json.junit.data.Singleton;
import org.json.junit.data.SingletonEnum; import org.json.junit.data.SingletonEnum;
import org.json.junit.data.WeirdList; import org.json.junit.data.WeirdList;
import org.junit.Test; import org.junit.Test;
import org.json.junit.Util;
import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
@@ -140,6 +114,10 @@ public class JSONObjectTest {
JSONObject first = new JSONObject("{\"a\": 1, \"b\": 2, \"c\": 3}"); JSONObject first = new JSONObject("{\"a\": 1, \"b\": 2, \"c\": 3}");
JSONObject second = new JSONObject("{\"a\": 1, \"b\": 2.0, \"c\": 4}"); JSONObject second = new JSONObject("{\"a\": 1, \"b\": 2.0, \"c\": 4}");
assertFalse("first-second should eval to false", first.similar(second)); assertFalse("first-second should eval to false", first.similar(second));
List<JSONObject> jsonObjects = new ArrayList<JSONObject>(
Arrays.asList(obj1, obj2, obj3, obj4, obj5)
);
Util.checkJSONObjectsMaps(jsonObjects);
} }
@Test @Test
@@ -214,7 +192,9 @@ public class JSONObjectTest {
*/ */
@Test(expected=NullPointerException.class) @Test(expected=NullPointerException.class)
public void jsonObjectByNullBean() { public void jsonObjectByNullBean() {
assertNull("Expected an exception",new JSONObject((MyBean)null)); JSONObject jsonObject = new JSONObject((MyBean)null);
assertNull("Expected an exception", jsonObject);
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -232,6 +212,7 @@ public class JSONObjectTest {
assertTrue("expected value1", textStr.contains("\"value1\"")); assertTrue("expected value1", textStr.contains("\"value1\""));
assertTrue("expected key2", textStr.contains("\"key2\"")); assertTrue("expected key2", textStr.contains("\"key2\""));
assertTrue("expected 42", textStr.contains("42")); assertTrue("expected 42", textStr.contains("42"));
Util.checkJSONObjectMaps(jsonObject);
} }
@Test @Test
@@ -252,6 +233,7 @@ public class JSONObjectTest {
final String actualString = json.optString("key"); final String actualString = json.optString("key");
assert str.equals(actualString) : "Incorrect key value. Got " assert str.equals(actualString) : "Incorrect key value. Got "
+ actualString + " expected " + str; + actualString + " expected " + str;
Util.checkJSONObjectMaps(json);
} }
/** /**
@@ -261,6 +243,7 @@ public class JSONObjectTest {
public void emptyJsonObject() { public void emptyJsonObject() {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
assertTrue("jsonObject should be empty", jsonObject.isEmpty()); assertTrue("jsonObject should be empty", jsonObject.isEmpty());
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -291,6 +274,7 @@ public class JSONObjectTest {
assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey"))); assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey")));
assertTrue("expected \"doubleKey\":-23.45e67", new BigDecimal("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); assertTrue("expected \"doubleKey\":-23.45e67", new BigDecimal("-23.45e67").equals(jsonObjectByName.query("/doubleKey")));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(jsonObject, jsonObjectByName)));
} }
/** /**
@@ -304,6 +288,7 @@ public class JSONObjectTest {
Map<String, Object> map = null; Map<String, Object> map = null;
JSONObject jsonObject = new JSONObject(map); JSONObject jsonObject = new JSONObject(map);
assertTrue("jsonObject should be empty", jsonObject.isEmpty()); assertTrue("jsonObject should be empty", jsonObject.isEmpty());
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -329,6 +314,7 @@ public class JSONObjectTest {
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey")));
assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -367,6 +353,9 @@ public class JSONObjectTest {
assertTrue( assertTrue(
"The RAW Collection should give me the same as the Typed Collection", "The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj)); expected.similar(jaObjObj));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(
Arrays.asList(jaRaw, jaStrObj, jaStrInt, jaObjObj))
);
} }
/** /**
@@ -384,8 +373,8 @@ public class JSONObjectTest {
* The only getter is getNumber (key=number), whose return value is * The only getter is getNumber (key=number), whose return value is
* BigDecimal(42). * BigDecimal(42).
*/ */
JSONObject jsonObject = new JSONObject(new MyNumberContainer()); JSONObject jsonObject0 = new JSONObject(new MyNumberContainer());
String actual = jsonObject.toString(); String actual = jsonObject0.toString();
String expected = "{\"myNumber\":{\"number\":42}}"; String expected = "{\"myNumber\":{\"number\":42}}";
assertEquals("Equal", expected , actual); assertEquals("Equal", expected , actual);
@@ -397,9 +386,9 @@ public class JSONObjectTest {
* The MyNumber.toString() method is responsible for * The MyNumber.toString() method is responsible for
* returning a reasonable value: the string '42'. * returning a reasonable value: the string '42'.
*/ */
jsonObject = new JSONObject(); JSONObject jsonObject1 = new JSONObject();
jsonObject.put("myNumber", new MyNumber()); jsonObject1.put("myNumber", new MyNumber());
actual = jsonObject.toString(); actual = jsonObject1.toString();
expected = "{\"myNumber\":42}"; expected = "{\"myNumber\":42}";
assertEquals("Equal", expected , actual); assertEquals("Equal", expected , actual);
@@ -411,8 +400,8 @@ public class JSONObjectTest {
* wrap() inserts the value as a string. That is why 42 comes back * wrap() inserts the value as a string. That is why 42 comes back
* wrapped in quotes. * wrapped in quotes.
*/ */
jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); JSONObject jsonObject2 = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42)));
actual = jsonObject.toString(); actual = jsonObject2.toString();
expected = "{\"myNumber\":\"42\"}"; expected = "{\"myNumber\":\"42\"}";
assertEquals("Equal", expected , actual); assertEquals("Equal", expected , actual);
@@ -422,9 +411,9 @@ public class JSONObjectTest {
* AtomicInteger is recognized as a Number, and converted via * AtomicInteger is recognized as a Number, and converted via
* numberToString() into the unquoted string '42'. * numberToString() into the unquoted string '42'.
*/ */
jsonObject = new JSONObject(); JSONObject jsonObject3 = new JSONObject();
jsonObject.put("myNumber", new AtomicInteger(42)); jsonObject3.put("myNumber", new AtomicInteger(42));
actual = jsonObject.toString(); actual = jsonObject3.toString();
expected = "{\"myNumber\":42}"; expected = "{\"myNumber\":42}";
assertEquals("Equal", expected , actual); assertEquals("Equal", expected , actual);
@@ -435,11 +424,11 @@ public class JSONObjectTest {
* bean and inserted into a contained JSONObject. It has 2 getters, * bean and inserted into a contained JSONObject. It has 2 getters,
* for numerator and denominator. * for numerator and denominator.
*/ */
jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2))); JSONObject jsonObject4 = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2)));
assertEquals(1, jsonObject.length()); assertEquals(1, jsonObject4.length());
assertEquals(2, ((JSONObject)(jsonObject.get("myNumber"))).length()); assertEquals(2, ((JSONObject)(jsonObject4.get("myNumber"))).length());
assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator")); assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject4.query("/myNumber/numerator"));
assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator")); assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject4.query("/myNumber/denominator"));
/** /**
* JSONObject.put() inserts the Fraction directly into the * JSONObject.put() inserts the Fraction directly into the
@@ -449,11 +438,15 @@ public class JSONObjectTest {
* BigDecimal sanity check fails, so writeValue() defaults * BigDecimal sanity check fails, so writeValue() defaults
* to returning a safe JSON quoted string. Pretty slick! * to returning a safe JSON quoted string. Pretty slick!
*/ */
jsonObject = new JSONObject(); JSONObject jsonObject5 = new JSONObject();
jsonObject.put("myNumber", new Fraction(4,2)); jsonObject5.put("myNumber", new Fraction(4,2));
actual = jsonObject.toString(); actual = jsonObject5.toString();
expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed
assertEquals("Equal", expected , actual); assertEquals("Equal", expected , actual);
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject0, jsonObject1, jsonObject2, jsonObject3, jsonObject4, jsonObject5
)));
} }
/** /**
@@ -488,6 +481,10 @@ public class JSONObjectTest {
assertTrue( assertTrue(
"The RAW Collection should give me the same as the Typed Collection", "The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaInt)); expected.similar(jaInt));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jaRaw, jaObj, jaInt
)));
} }
@@ -531,6 +528,10 @@ public class JSONObjectTest {
assertTrue( assertTrue(
"The RAW Collection should give me the same as the Typed Collection", "The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj)); expected.similar(jaObjObj));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jaRaw, jaStrObj, jaStrInt, jaStrObj
)));
} }
@@ -553,6 +554,7 @@ public class JSONObjectTest {
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 0 key1 items", ((Map<?,?>)(JsonPath.read(doc, "$.key1"))).size() == 0); assertTrue("expected 0 key1 items", ((Map<?,?>)(JsonPath.read(doc, "$.key1"))).size() == 0);
assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2"))); assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -580,6 +582,7 @@ public class JSONObjectTest {
assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey"))); assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey")));
assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -620,6 +623,7 @@ public class JSONObjectTest {
assertTrue("expected 2 callbacks items", ((List<?>)(JsonPath.read(doc, "$.callbacks"))).size() == 2); assertTrue("expected 2 callbacks items", ((List<?>)(JsonPath.read(doc, "$.callbacks"))).size() == 2);
assertTrue("expected 0 handler items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); assertTrue("expected 0 handler items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0);
assertTrue("expected 0 callbacks[1] items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); assertTrue("expected 0 callbacks[1] items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0);
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -655,6 +659,7 @@ public class JSONObjectTest {
// InterfaceField replaces someFloat property name via user-defined annotation // InterfaceField replaces someFloat property name via user-defined annotation
assertTrue("Overridden String field name (InterfaceField) should have been found", assertTrue("Overridden String field name (InterfaceField) should have been found",
jsonObject.has("InterfaceField")); jsonObject.has("InterfaceField"));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -705,6 +710,7 @@ public class JSONObjectTest {
// property name able was replaced by Getable via user-defined annotation // property name able was replaced by Getable via user-defined annotation
assertTrue("Overridden boolean field name (Getable) should have been found", assertTrue("Overridden boolean field name (Getable) should have been found",
jsonObject.has("Getable")); jsonObject.has("Getable"));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -725,6 +731,7 @@ public class JSONObjectTest {
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString"))); assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString")));
assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt"))); assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -746,6 +753,7 @@ public class JSONObjectTest {
assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2); assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2);
assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later"))); assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later")));
assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator"))); assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -778,6 +786,7 @@ public class JSONObjectTest {
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3")));
assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4")));
assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -809,6 +818,7 @@ public class JSONObjectTest {
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3")));
assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4")));
assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -944,6 +954,7 @@ public class JSONObjectTest {
JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey");
assertTrue("objectKey should be JSONObject", assertTrue("objectKey should be JSONObject",
jsonObjectInner.get("myKey").equals("myVal")); jsonObjectInner.get("myKey").equals("myVal"));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -1006,6 +1017,7 @@ public class JSONObjectTest {
obj = jsonObject.get( "largeExponent" ); obj = jsonObject.get( "largeExponent" );
assertTrue("largeExponent should evaluate as a BigDecimal", assertTrue("largeExponent should evaluate as a BigDecimal",
new BigDecimal("-23.45e2327").equals(obj)); new BigDecimal("-23.45e2327").equals(obj));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -1054,6 +1066,7 @@ public class JSONObjectTest {
jsonObject.get("floatIdentifier").equals(Double.valueOf(0.1))); jsonObject.get("floatIdentifier").equals(Double.valueOf(0.1)));
assertTrue("doubleIdentifier currently evaluates to double 0.1", assertTrue("doubleIdentifier currently evaluates to double 0.1",
jsonObject.get("doubleIdentifier").equals(Double.valueOf(0.1))); jsonObject.get("doubleIdentifier").equals(Double.valueOf(0.1)));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -1090,7 +1103,7 @@ public class JSONObjectTest {
fail("Expected an exception"); fail("Expected an exception");
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a Boolean.", "JSONObject[\"stringKey\"] is not a Boolean (class java.lang.String : hello world!).",
e.getMessage()); e.getMessage());
} }
try { try {
@@ -1106,7 +1119,7 @@ public class JSONObjectTest {
fail("Expected an exception"); fail("Expected an exception");
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONObject[\"trueKey\"] is not a string.", "JSONObject[\"trueKey\"] is not a string (class java.lang.Boolean : true).",
e.getMessage()); e.getMessage());
} }
try { try {
@@ -1122,7 +1135,7 @@ public class JSONObjectTest {
fail("Expected an exception"); fail("Expected an exception");
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a double.", "JSONObject[\"stringKey\"] is not a double (class java.lang.String : hello world!).",
e.getMessage()); e.getMessage());
} }
try { try {
@@ -1138,7 +1151,7 @@ public class JSONObjectTest {
fail("Expected an exception"); fail("Expected an exception");
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a float.", "JSONObject[\"stringKey\"] is not a float (class java.lang.String : hello world!).",
e.getMessage()); e.getMessage());
} }
try { try {
@@ -1154,7 +1167,7 @@ public class JSONObjectTest {
fail("Expected an exception"); fail("Expected an exception");
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a int.", "JSONObject[\"stringKey\"] is not a int (class java.lang.String : hello world!).",
e.getMessage()); e.getMessage());
} }
try { try {
@@ -1170,7 +1183,7 @@ public class JSONObjectTest {
fail("Expected an exception"); fail("Expected an exception");
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a long.", "JSONObject[\"stringKey\"] is not a long (class java.lang.String : hello world!).",
e.getMessage()); e.getMessage());
} }
try { try {
@@ -1186,7 +1199,7 @@ public class JSONObjectTest {
fail("Expected an exception"); fail("Expected an exception");
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a JSONArray.", "JSONObject[\"stringKey\"] is not a JSONArray (class java.lang.String : hello world!).",
e.getMessage()); e.getMessage());
} }
try { try {
@@ -1202,9 +1215,10 @@ public class JSONObjectTest {
fail("Expected an exception"); fail("Expected an exception");
} catch (JSONException e) { } catch (JSONException e) {
assertEquals("Expecting an exception message", assertEquals("Expecting an exception message",
"JSONObject[\"stringKey\"] is not a JSONObject.", "JSONObject[\"stringKey\"] is not a JSONObject (class java.lang.String : hello world!).",
e.getMessage()); e.getMessage());
} }
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -1232,6 +1246,7 @@ public class JSONObjectTest {
assertTrue("3.0 can still be interpreted as a double", assertTrue("3.0 can still be interpreted as a double",
deserialized.getDouble(key30) == 3.0); deserialized.getDouble(key30) == 3.0);
assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1);
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -1247,9 +1262,9 @@ public class JSONObjectTest {
* value is stored. This should be fixed. * value is stored. This should be fixed.
*/ */
BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); BigInteger bigInteger = new BigInteger("123456789012345678901234567890");
JSONObject jsonObject = new JSONObject(bigInteger); JSONObject jsonObject0 = new JSONObject(bigInteger);
Object obj = jsonObject.get("lowestSetBit"); Object obj = jsonObject0.get("lowestSetBit");
assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); assertTrue("JSONObject only has 1 value", jsonObject0.length() == 1);
assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet",
obj instanceof Integer); obj instanceof Integer);
assertTrue("this bigInteger lowestBitSet happens to be 1", assertTrue("this bigInteger lowestBitSet happens to be 1",
@@ -1262,57 +1277,57 @@ public class JSONObjectTest {
*/ */
BigDecimal bigDecimal = new BigDecimal( BigDecimal bigDecimal = new BigDecimal(
"123456789012345678901234567890.12345678901234567890123456789"); "123456789012345678901234567890.12345678901234567890123456789");
jsonObject = new JSONObject(bigDecimal); JSONObject jsonObject1 = new JSONObject(bigDecimal);
assertTrue("large bigDecimal is not stored", jsonObject.isEmpty()); assertTrue("large bigDecimal is not stored", jsonObject1.isEmpty());
/** /**
* JSONObject put(String, Object) method stores and serializes * JSONObject put(String, Object) method stores and serializes
* bigInt and bigDec correctly. Nothing needs to change. * bigInt and bigDec correctly. Nothing needs to change.
*/ */
jsonObject = new JSONObject(); JSONObject jsonObject2 = new JSONObject();
jsonObject.put("bigInt", bigInteger); jsonObject2.put("bigInt", bigInteger);
assertTrue("jsonObject.put() handles bigInt correctly", assertTrue("jsonObject.put() handles bigInt correctly",
jsonObject.get("bigInt").equals(bigInteger)); jsonObject2.get("bigInt").equals(bigInteger));
assertTrue("jsonObject.getBigInteger() handles bigInt correctly", assertTrue("jsonObject.getBigInteger() handles bigInt correctly",
jsonObject.getBigInteger("bigInt").equals(bigInteger)); jsonObject2.getBigInteger("bigInt").equals(bigInteger));
assertTrue("jsonObject.optBigInteger() handles bigInt correctly", assertTrue("jsonObject.optBigInteger() handles bigInt correctly",
jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); jsonObject2.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger));
assertTrue("jsonObject serializes bigInt correctly", assertTrue("jsonObject serializes bigInt correctly",
jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); jsonObject2.toString().equals("{\"bigInt\":123456789012345678901234567890}"));
assertTrue("BigInteger as BigDecimal", assertTrue("BigInteger as BigDecimal",
jsonObject.getBigDecimal("bigInt").equals(new BigDecimal(bigInteger))); jsonObject2.getBigDecimal("bigInt").equals(new BigDecimal(bigInteger)));
jsonObject = new JSONObject(); JSONObject jsonObject3 = new JSONObject();
jsonObject.put("bigDec", bigDecimal); jsonObject3.put("bigDec", bigDecimal);
assertTrue("jsonObject.put() handles bigDec correctly", assertTrue("jsonObject.put() handles bigDec correctly",
jsonObject.get("bigDec").equals(bigDecimal)); jsonObject3.get("bigDec").equals(bigDecimal));
assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", assertTrue("jsonObject.getBigDecimal() handles bigDec correctly",
jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); jsonObject3.getBigDecimal("bigDec").equals(bigDecimal));
assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", assertTrue("jsonObject.optBigDecimal() handles bigDec correctly",
jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); jsonObject3.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal));
assertTrue("jsonObject serializes bigDec correctly", assertTrue("jsonObject serializes bigDec correctly",
jsonObject.toString().equals( jsonObject3.toString().equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
assertTrue("BigDecimal as BigInteger", assertTrue("BigDecimal as BigInteger",
jsonObject.getBigInteger("bigDec").equals(bigDecimal.toBigInteger())); jsonObject3.getBigInteger("bigDec").equals(bigDecimal.toBigInteger()));
/** /**
* exercise some exceptions * exercise some exceptions
*/ */
try { try {
// bigInt key does not exist // bigInt key does not exist
jsonObject.getBigDecimal("bigInt"); jsonObject3.getBigDecimal("bigInt");
fail("expected an exeption"); fail("expected an exeption");
} catch (JSONException ignored) {} } catch (JSONException ignored) {}
obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); obj = jsonObject3.optBigDecimal("bigInt", BigDecimal.ONE);
assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE));
jsonObject.put("stringKey", "abc"); jsonObject3.put("stringKey", "abc");
try { try {
jsonObject.getBigDecimal("stringKey"); jsonObject3.getBigDecimal("stringKey");
fail("expected an exeption"); fail("expected an exeption");
} catch (JSONException ignored) {} } catch (JSONException ignored) {}
obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); obj = jsonObject3.optBigInteger("bigDec", BigInteger.ONE);
assertTrue("expected BigInteger", obj instanceof BigInteger); assertTrue("expected BigInteger", obj instanceof BigInteger);
assertEquals(bigDecimal.toBigInteger(), obj); assertEquals(bigDecimal.toBigInteger(), obj);
@@ -1345,79 +1360,79 @@ public class JSONObjectTest {
// bigInt map ctor // bigInt map ctor
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
map.put("bigInt", bigInteger); map.put("bigInt", bigInteger);
jsonObject = new JSONObject(map); JSONObject jsonObject4 = new JSONObject(map);
String actualFromMapStr = jsonObject.toString(); String actualFromMapStr = jsonObject4.toString();
assertTrue("bigInt in map (or array or bean) is a string", assertTrue("bigInt in map (or array or bean) is a string",
actualFromMapStr.equals( actualFromMapStr.equals(
"{\"bigInt\":123456789012345678901234567890}")); "{\"bigInt\":123456789012345678901234567890}"));
// bigInt put // bigInt put
jsonObject = new JSONObject(); JSONObject jsonObject5 = new JSONObject();
jsonObject.put("bigInt", bigInteger); jsonObject5.put("bigInt", bigInteger);
String actualFromPutStr = jsonObject.toString(); String actualFromPutStr = jsonObject5.toString();
assertTrue("bigInt from put is a number", assertTrue("bigInt from put is a number",
actualFromPutStr.equals( actualFromPutStr.equals(
"{\"bigInt\":123456789012345678901234567890}")); "{\"bigInt\":123456789012345678901234567890}"));
// bigDec map ctor // bigDec map ctor
map = new HashMap<String, Object>(); map = new HashMap<String, Object>();
map.put("bigDec", bigDecimal); map.put("bigDec", bigDecimal);
jsonObject = new JSONObject(map); JSONObject jsonObject6 = new JSONObject(map);
actualFromMapStr = jsonObject.toString(); actualFromMapStr = jsonObject6.toString();
assertTrue("bigDec in map (or array or bean) is a bigDec", assertTrue("bigDec in map (or array or bean) is a bigDec",
actualFromMapStr.equals( actualFromMapStr.equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
// bigDec put // bigDec put
jsonObject = new JSONObject(); JSONObject jsonObject7 = new JSONObject();
jsonObject.put("bigDec", bigDecimal); jsonObject7.put("bigDec", bigDecimal);
actualFromPutStr = jsonObject.toString(); actualFromPutStr = jsonObject7.toString();
assertTrue("bigDec from put is a number", assertTrue("bigDec from put is a number",
actualFromPutStr.equals( actualFromPutStr.equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
// bigInt,bigDec put // bigInt,bigDec put
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray0 = new JSONArray();
jsonArray.put(bigInteger); jsonArray0.put(bigInteger);
jsonArray.put(bigDecimal); jsonArray0.put(bigDecimal);
actualFromPutStr = jsonArray.toString(); actualFromPutStr = jsonArray0.toString();
assertTrue("bigInt, bigDec from put is a number", assertTrue("bigInt, bigDec from put is a number",
actualFromPutStr.equals( actualFromPutStr.equals(
"[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]"));
assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger)); assertTrue("getBigInt is bigInt", jsonArray0.getBigInteger(0).equals(bigInteger));
assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal)); assertTrue("getBigDec is bigDec", jsonArray0.getBigDecimal(1).equals(bigDecimal));
assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); assertTrue("optBigInt is bigInt", jsonArray0.optBigInteger(0, BigInteger.ONE).equals(bigInteger));
assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); assertTrue("optBigDec is bigDec", jsonArray0.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal));
jsonArray.put(Boolean.TRUE); jsonArray0.put(Boolean.TRUE);
try { try {
jsonArray.getBigInteger(2); jsonArray0.getBigInteger(2);
fail("should not be able to get big int"); fail("should not be able to get big int");
} catch (Exception ignored) {} } catch (Exception ignored) {}
try { try {
jsonArray.getBigDecimal(2); jsonArray0.getBigDecimal(2);
fail("should not be able to get big dec"); fail("should not be able to get big dec");
} catch (Exception ignored) {} } catch (Exception ignored) {}
assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); assertTrue("optBigInt is default", jsonArray0.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE));
assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); assertTrue("optBigDec is default", jsonArray0.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE));
// bigInt,bigDec list ctor // bigInt,bigDec list ctor
List<Object> list = new ArrayList<Object>(); List<Object> list = new ArrayList<Object>();
list.add(bigInteger); list.add(bigInteger);
list.add(bigDecimal); list.add(bigDecimal);
jsonArray = new JSONArray(list); JSONArray jsonArray1 = new JSONArray(list);
String actualFromListStr = jsonArray.toString(); String actualFromListStr = jsonArray1.toString();
assertTrue("bigInt, bigDec in list is a bigInt, bigDec", assertTrue("bigInt, bigDec in list is a bigInt, bigDec",
actualFromListStr.equals( actualFromListStr.equals(
"[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]"));
// bigInt bean ctor // bigInt bean ctor
MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class);
when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890"));
jsonObject = new JSONObject(myBigNumberBean); JSONObject jsonObject8 = new JSONObject(myBigNumberBean);
String actualFromBeanStr = jsonObject.toString(); String actualFromBeanStr = jsonObject8.toString();
// can't do a full string compare because mockery adds an extra key/value // can't do a full string compare because mockery adds an extra key/value
assertTrue("bigInt from bean ctor is a bigInt", assertTrue("bigInt from bean ctor is a bigInt",
actualFromBeanStr.contains("123456789012345678901234567890")); actualFromBeanStr.contains("123456789012345678901234567890"));
// bigDec bean ctor // bigDec bean ctor
myBigNumberBean = mock(MyBigNumberBean.class); myBigNumberBean = mock(MyBigNumberBean.class);
when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789"));
jsonObject = new JSONObject(myBigNumberBean); jsonObject8 = new JSONObject(myBigNumberBean);
actualFromBeanStr = jsonObject.toString(); actualFromBeanStr = jsonObject8.toString();
// can't do a full string compare because mockery adds an extra key/value // can't do a full string compare because mockery adds an extra key/value
assertTrue("bigDec from bean ctor is a bigDec", assertTrue("bigDec from bean ctor is a bigDec",
actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789"));
@@ -1426,7 +1441,12 @@ public class JSONObjectTest {
assertTrue("wrap() returns big num",obj.equals(bigInteger)); assertTrue("wrap() returns big num",obj.equals(bigInteger));
obj = JSONObject.wrap(bigDecimal); obj = JSONObject.wrap(bigDecimal);
assertTrue("wrap() returns string",obj.equals(bigDecimal)); assertTrue("wrap() returns string",obj.equals(bigDecimal));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject0, jsonObject1, jsonObject2, jsonObject3, jsonObject4,
jsonObject5, jsonObject6, jsonObject7, jsonObject8
)));
Util.checkJSONArrayMaps(jsonArray0, jsonObject0.getMapType());
Util.checkJSONArrayMaps(jsonArray1, jsonObject0.getMapType());
} }
/** /**
@@ -1438,7 +1458,6 @@ public class JSONObjectTest {
*/ */
@Test @Test
public void jsonObjectNames() { public void jsonObjectNames() {
JSONObject jsonObject;
// getNames() from null JSONObject // getNames() from null JSONObject
assertTrue("null names from null Object", assertTrue("null names from null Object",
@@ -1449,16 +1468,16 @@ public class JSONObjectTest {
null == JSONObject.getNames(new MyJsonString())); null == JSONObject.getNames(new MyJsonString()));
// getNames from new JSONOjbect // getNames from new JSONOjbect
jsonObject = new JSONObject(); JSONObject jsonObject0 = new JSONObject();
String [] names = JSONObject.getNames(jsonObject); String [] names = JSONObject.getNames(jsonObject0);
assertTrue("names should be null", names == null); assertTrue("names should be null", names == null);
// getNames() from empty JSONObject // getNames() from empty JSONObject
String emptyStr = "{}"; String emptyStr = "{}";
jsonObject = new JSONObject(emptyStr); JSONObject jsonObject1 = new JSONObject(emptyStr);
assertTrue("empty JSONObject should have null names", assertTrue("empty JSONObject should have null names",
null == JSONObject.getNames(jsonObject)); null == JSONObject.getNames(jsonObject1));
// getNames() from JSONObject // getNames() from JSONObject
String str = String str =
@@ -1467,13 +1486,13 @@ public class JSONObjectTest {
"\"falseKey\":false,"+ "\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+ "\"stringKey\":\"hello world!\","+
"}"; "}";
jsonObject = new JSONObject(str); JSONObject jsonObject2 = new JSONObject(str);
names = JSONObject.getNames(jsonObject); names = JSONObject.getNames(jsonObject2);
JSONArray jsonArray = new JSONArray(names); JSONArray jsonArray0 = new JSONArray(names);
// validate JSON // validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider() Object doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString()); .parse(jsonArray0.toString());
List<?> docList = JsonPath.read(doc, "$"); List<?> docList = JsonPath.read(doc, "$");
assertTrue("expected 3 items", docList.size() == 3); assertTrue("expected 3 items", docList.size() == 3);
assertTrue( assertTrue(
@@ -1494,9 +1513,9 @@ public class JSONObjectTest {
names = JSONObject.getNames(myEnumField); names = JSONObject.getNames(myEnumField);
// validate JSON // validate JSON
jsonArray = new JSONArray(names); JSONArray jsonArray1 = new JSONArray(names);
doc = Configuration.defaultConfiguration().jsonProvider() doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString()); .parse(jsonArray1.toString());
docList = JsonPath.read(doc, "$"); docList = JsonPath.read(doc, "$");
assertTrue("expected 3 items", docList.size() == 3); assertTrue("expected 3 items", docList.size() == 3);
assertTrue( assertTrue(
@@ -1518,9 +1537,9 @@ public class JSONObjectTest {
names = JSONObject.getNames(myPublicClass); names = JSONObject.getNames(myPublicClass);
// validate JSON // validate JSON
jsonArray = new JSONArray(names); JSONArray jsonArray2 = new JSONArray(names);
doc = Configuration.defaultConfiguration().jsonProvider() doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString()); .parse(jsonArray2.toString());
docList = JsonPath.read(doc, "$"); docList = JsonPath.read(doc, "$");
assertTrue("expected 2 items", docList.size() == 2); assertTrue("expected 2 items", docList.size() == 2);
assertTrue( assertTrue(
@@ -1529,6 +1548,12 @@ public class JSONObjectTest {
assertTrue( assertTrue(
"expected to find publicInt", "expected to find publicInt",
((List<?>) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); ((List<?>) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1);
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject0, jsonObject1, jsonObject2
)));
Util.checkJSONArrayMaps(jsonArray0, jsonObject0.getMapType());
Util.checkJSONArrayMaps(jsonArray1, jsonObject0.getMapType());
Util.checkJSONArrayMaps(jsonArray2, jsonObject0.getMapType());
} }
/** /**
@@ -1540,6 +1565,8 @@ public class JSONObjectTest {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.names(); JSONArray jsonArray = jsonObject.names();
assertTrue("jsonArray should be null", jsonArray == null); assertTrue("jsonArray should be null", jsonArray == null);
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType());
} }
/** /**
@@ -1564,6 +1591,8 @@ public class JSONObjectTest {
assertTrue("expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); assertTrue("expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1);
assertTrue("expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); assertTrue("expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1);
assertTrue("expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); assertTrue("expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1);
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType());
} }
/** /**
@@ -1682,7 +1711,9 @@ public class JSONObjectTest {
// this.put(key, new Float((Float) value + 1)); // this.put(key, new Float((Float) value + 1));
// Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not
// really in the scope of a JSON-library (IMHO.) // really in the scope of a JSON-library (IMHO.)
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, inc
)));
} }
/** /**
@@ -1780,6 +1811,12 @@ public class JSONObjectTest {
JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr);
assertTrue("different nested JSONArrays should not be similar", assertTrue("different nested JSONArrays should not be similar",
!aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); !aCompareArrayJsonObject.similar(bCompareArrayJsonObject));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, expectedJsonObject, aCompareValueJsonObject,
aCompareArrayJsonObject, aCompareObjectJsonObject, aCompareArrayJsonObject,
bCompareValueJsonObject, bCompareArrayJsonObject, bCompareObjectJsonObject,
bCompareArrayJsonObject
)));
} }
/** /**
@@ -1815,6 +1852,7 @@ public class JSONObjectTest {
assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2")));
assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3")));
assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -1888,6 +1926,9 @@ public class JSONObjectTest {
JSONObject jo = new JSONObject().put("TABLE", new JSONObject().put("yhoo", new JSONObject())); JSONObject jo = new JSONObject().put("TABLE", new JSONObject().put("yhoo", new JSONObject()));
assertEquals("toString(2)","{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2)); assertEquals("toString(2)","{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, jo
)));
} }
/** /**
@@ -1909,6 +1950,7 @@ public class JSONObjectTest {
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 1 key item", ((Map<?,?>)(JsonPath.read(doc, "$.key"))).size() == 1); assertTrue("expected 1 key item", ((Map<?,?>)(JsonPath.read(doc, "$.key"))).size() == 1);
assertTrue("expected def", "def".equals(jsonObject.query("/key/abc"))); assertTrue("expected def", "def".equals(jsonObject.query("/key/abc")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -1931,6 +1973,7 @@ public class JSONObjectTest {
assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 1 key item", ((List<?>)(JsonPath.read(doc, "$.key"))).size() == 1); assertTrue("expected 1 key item", ((List<?>)(JsonPath.read(doc, "$.key"))).size() == 1);
assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0"))); assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -1979,6 +2022,8 @@ public class JSONObjectTest {
Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; Integer[] array = { new Integer(1), new Integer(2), new Integer(3) };
assertTrue("array valueToString() incorrect", assertTrue("array valueToString() incorrect",
jsonArray.toString().equals(JSONObject.valueToString(array))); jsonArray.toString().equals(JSONObject.valueToString(array)));
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType());
} }
/** /**
@@ -2082,6 +2127,11 @@ public class JSONObjectTest {
assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1"))); assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1")));
assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2"))); assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2")));
assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3"))); assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3")));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, mapJsonObject
)));
Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType());
Util.checkJSONArrayMaps(integerArrayJsonArray, jsonObject.getMapType());
} }
@@ -2096,6 +2146,7 @@ public class JSONObjectTest {
try { try {
JSONObject jo = new JSONObject(source); JSONObject jo = new JSONObject(source);
assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key"))); assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key")));
Util.checkJSONObjectMaps(jo);
} catch (JSONException ex) { } catch (JSONException ex) {
assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error", assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error",
i=='\0' || i=='\n' || i=='\r' i=='\0' || i=='\n' || i=='\r'
@@ -2395,6 +2446,7 @@ public class JSONObjectTest {
assertTrue("jsonObject should be empty", jsonObject.isEmpty()); assertTrue("jsonObject should be empty", jsonObject.isEmpty());
jsonObject.putOnce(null, ""); jsonObject.putOnce(null, "");
assertTrue("jsonObject should be empty", jsonObject.isEmpty()); assertTrue("jsonObject should be empty", jsonObject.isEmpty());
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -2430,6 +2482,7 @@ public class JSONObjectTest {
42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue()); 42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue());
assertTrue("optString() should return default string", assertTrue("optString() should return default string",
"hi".equals(jsonObject.optString("hiKey", "hi"))); "hi".equals(jsonObject.optString("hiKey", "hi")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -2466,6 +2519,7 @@ public class JSONObjectTest {
42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue()); 42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue());
assertTrue("optString() should return default string", assertTrue("optString() should return default string",
"hi".equals(jsonObject.optString("hiKey", "hi"))); "hi".equals(jsonObject.optString("hiKey", "hi")));
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -2484,6 +2538,7 @@ public class JSONObjectTest {
assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0);
assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0);
assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l); assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l);
Util.checkJSONObjectMaps(jo);
} }
/** /**
@@ -2518,6 +2573,7 @@ public class JSONObjectTest {
assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumberStr")); assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumberStr"));
assertEquals(19007199254740992l, (long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); assertEquals(19007199254740992l, (long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"));
assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"));
Util.checkJSONObjectMaps(jo);
} }
/** /**
@@ -2540,6 +2596,7 @@ public class JSONObjectTest {
assertNull(jo.optBigDecimal("nullVal", null)); assertNull(jo.optBigDecimal("nullVal", null));
assertEquals(jo.optBigDecimal("float", null),jo.getBigDecimal("float")); assertEquals(jo.optBigDecimal("float", null),jo.getBigDecimal("float"));
assertEquals(jo.optBigDecimal("double", null),jo.getBigDecimal("double")); assertEquals(jo.optBigDecimal("double", null),jo.getBigDecimal("double"));
Util.checkJSONObjectMaps(jo);
} }
/** /**
@@ -2560,6 +2617,7 @@ public class JSONObjectTest {
assertEquals(new BigInteger("1234"),jo.optBigInteger("bigInteger", null)); assertEquals(new BigInteger("1234"),jo.optBigInteger("bigInteger", null));
assertEquals(new BigInteger("1234"),jo.optBigInteger("bigDecimal", null)); assertEquals(new BigInteger("1234"),jo.optBigInteger("bigDecimal", null));
assertNull(jo.optBigDecimal("nullVal", null)); assertNull(jo.optBigDecimal("nullVal", null));
Util.checkJSONObjectMaps(jo);
} }
/** /**
@@ -2577,8 +2635,9 @@ public class JSONObjectTest {
JSONObject jsonObjectPutNull = new JSONObject(str); JSONObject jsonObjectPutNull = new JSONObject(str);
jsonObjectPutNull.put("myKey", (Object) null); jsonObjectPutNull.put("myKey", (Object) null);
assertTrue("jsonObject should be empty", jsonObjectPutNull.isEmpty()); assertTrue("jsonObject should be empty", jsonObjectPutNull.isEmpty());
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObjectRemove, jsonObjectPutNull
)));
} }
/** /**
@@ -2663,6 +2722,7 @@ public class JSONObjectTest {
} finally { } finally {
stringWriter.close(); stringWriter.close();
} }
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -2745,7 +2805,7 @@ public class JSONObjectTest {
writer.close(); writer.close();
} catch (Exception e) {} } catch (Exception e) {}
} }
Util.checkJSONObjectMaps(jsonObject);
} }
@@ -2813,6 +2873,7 @@ public class JSONObjectTest {
stringWriter.close(); stringWriter.close();
} catch (Exception e) {} } catch (Exception e) {}
} }
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -2855,6 +2916,7 @@ public class JSONObjectTest {
JSONObject aJsonObject = new JSONObject(str); JSONObject aJsonObject = new JSONObject(str);
assertTrue("Same JSONObject should be equal to itself", assertTrue("Same JSONObject should be equal to itself",
aJsonObject.equals(aJsonObject)); aJsonObject.equals(aJsonObject));
Util.checkJSONObjectMaps(aJsonObject);
} }
/** /**
@@ -2940,6 +3002,9 @@ public class JSONObjectTest {
"<key>null</key>".equals(sJONull)); "<key>null</key>".equals(sJONull));
String sNull = XML.toString(jsonObjectNull); String sNull = XML.toString(jsonObjectNull);
assertTrue("null should emit an empty string", "".equals(sNull)); assertTrue("null should emit an empty string", "".equals(sNull));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObjectJONull, jsonObjectNull
)));
} }
@Test(expected = JSONPointerException.class) @Test(expected = JSONPointerException.class)
@@ -3037,6 +3102,7 @@ public class JSONObjectTest {
// assert that the new map is mutable // assert that the new map is mutable
assertTrue("Removing a key should succeed", map.remove("key3") != null); assertTrue("Removing a key should succeed", map.remove("key3") != null);
assertTrue("Map should have 2 elements", map.size() == 2); assertTrue("Map should have 2 elements", map.size() == 2);
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -3061,6 +3127,9 @@ public class JSONObjectTest {
// ensure our original jo hasn't changed. // ensure our original jo hasn't changed.
assertEquals(0, jo.get("someInt")); assertEquals(0, jo.get("someInt"));
assertEquals(null, jo.opt("someString")); assertEquals(null, jo.opt("someString"));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jo, jo2
)));
} }
/** /**
@@ -3085,6 +3154,9 @@ public class JSONObjectTest {
// ensure our original jo hasn't changed. // ensure our original jo hasn't changed.
assertEquals(0, jo.get("someInt")); assertEquals(0, jo.get("someInt"));
assertEquals(null, jo.opt("someString")); assertEquals(null, jo.opt("someString"));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jo, jo2
)));
} }
/** /**
@@ -3100,6 +3172,7 @@ public class JSONObjectTest {
assertEquals("Expected the getter to only be called once", assertEquals("Expected the getter to only be called once",
1, bean.genericGetCounter); 1, bean.genericGetCounter);
assertEquals(0, bean.genericSetCounter); assertEquals(0, bean.genericSetCounter);
Util.checkJSONObjectMaps(jo);
} }
/** /**
@@ -3115,6 +3188,7 @@ public class JSONObjectTest {
assertEquals("Expected the getter to only be called once", assertEquals("Expected the getter to only be called once",
1, bean.genericGetCounter); 1, bean.genericGetCounter);
assertEquals(0, bean.genericSetCounter); assertEquals(0, bean.genericSetCounter);
Util.checkJSONObjectMaps(jo);
} }
/** /**
@@ -3133,6 +3207,7 @@ public class JSONObjectTest {
assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(), assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(),
1, jo.length()); 1, jo.length());
assertNotNull(jo.get("ALL")); assertNotNull(jo.get("ALL"));
Util.checkJSONObjectMaps(jo);
} }
/** /**
@@ -3150,6 +3225,8 @@ public class JSONObjectTest {
BigDecimal wantedValue = BigDecimal.valueOf(value); BigDecimal wantedValue = BigDecimal.valueOf(value);
assertEquals(current, wantedValue); assertEquals(current, wantedValue);
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(array, jsonObject.getMapType());
} }
/** /**
@@ -3163,6 +3240,7 @@ public class JSONObjectTest {
1, jo.length()); 1, jo.length());
assertTrue(jo.get("closeable") instanceof JSONObject); assertTrue(jo.get("closeable") instanceof JSONObject);
assertTrue(jo.getJSONObject("closeable").has("string")); assertTrue(jo.getJSONObject("closeable").has("string"));
Util.checkJSONObjectMaps(jo);
} }
@Test(expected=NullPointerException.class) @Test(expected=NullPointerException.class)
@@ -3289,9 +3367,12 @@ public class JSONObjectTest {
ObjC.setRef(ObjA); ObjC.setRef(ObjA);
ObjB.setRef(ObjA); ObjB.setRef(ObjA);
ObjB.setRef2(ObjA); ObjB.setRef2(ObjA);
new JSONObject(ObjC); JSONObject j0 = new JSONObject(ObjC);
new JSONObject(ObjB); JSONObject j1 = new JSONObject(ObjB);
new JSONObject(ObjA); JSONObject j2 = new JSONObject(ObjA);
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
j0, j1, j2
)));
} }
@Test @Test
public void testLongRepeatObjectNotRecursive() { public void testLongRepeatObjectNotRecursive() {
@@ -3307,17 +3388,21 @@ public class JSONObjectTest {
ObjB.setRef2(ObjD); ObjB.setRef2(ObjD);
ObjA.setRef(ObjD); ObjA.setRef(ObjD);
ObjD.setRef(ObjE); ObjD.setRef(ObjE);
new JSONObject(ObjC); JSONObject j0 = new JSONObject(ObjC);
new JSONObject(ObjB); JSONObject j1 = new JSONObject(ObjB);
new JSONObject(ObjA); JSONObject j2 = new JSONObject(ObjA);
new JSONObject(ObjD); JSONObject j3 = new JSONObject(ObjD);
new JSONObject(ObjE); JSONObject j4 = new JSONObject(ObjE);
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
j0, j1, j2, j3, j4
)));
} }
@Test(expected=JSONException.class) @Test(expected=JSONException.class)
public void testRecursiveEquals() { public void testRecursiveEquals() {
RecursiveBeanEquals a = new RecursiveBeanEquals("same"); RecursiveBeanEquals a = new RecursiveBeanEquals("same");
a.setRef(a); a.setRef(a);
new JSONObject(a); JSONObject j0 = new JSONObject(a);
Util.checkJSONObjectMaps(j0);
} }
@Test @Test
public void testNotRecursiveEquals() { public void testNotRecursiveEquals() {
@@ -3326,7 +3411,8 @@ public class JSONObjectTest {
RecursiveBeanEquals c = new RecursiveBeanEquals("same"); RecursiveBeanEquals c = new RecursiveBeanEquals("same");
a.setRef(b); a.setRef(b);
b.setRef(c); b.setRef(c);
new JSONObject(a); JSONObject j0 = new JSONObject(a);
Util.checkJSONObjectMaps(j0);
} }
@@ -3336,6 +3422,7 @@ public class JSONObjectTest {
assertTrue("missing expected key 'empty_json_array'", jsonObject.has("empty_json_array")); assertTrue("missing expected key 'empty_json_array'", jsonObject.has("empty_json_array"));
assertNotNull("'empty_json_array' should be an array", jsonObject.getJSONArray("empty_json_array")); assertNotNull("'empty_json_array' should be an array", jsonObject.getJSONArray("empty_json_array"));
assertEquals("'empty_json_array' should have a length of 0", 0, jsonObject.getJSONArray("empty_json_array").length()); assertEquals("'empty_json_array' should have a length of 0", 0, jsonObject.getJSONArray("empty_json_array").length());
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -3351,6 +3438,7 @@ public class JSONObjectTest {
jsonObject.clear(); //Clears the JSONObject jsonObject.clear(); //Clears the JSONObject
assertTrue("expected jsonObject.length() == 0", jsonObject.length() == 0); //Check if its length is 0 assertTrue("expected jsonObject.length() == 0", jsonObject.length() == 0); //Check if its length is 0
jsonObject.getInt("key1"); //Should throws org.json.JSONException: JSONObject["asd"] not found jsonObject.getInt("key1"); //Should throws org.json.JSONException: JSONObject["asd"] not found
Util.checkJSONObjectMaps(jsonObject);
} }
/** /**
@@ -3364,6 +3452,7 @@ public class JSONObjectTest {
JSONObject json_input = new JSONObject(input); JSONObject json_input = new JSONObject(input);
assertNotNull(json_input); assertNotNull(json_input);
fail("Excepected Exception."); fail("Excepected Exception.");
Util.checkJSONObjectMaps(json_input);
} }
/** /**
@@ -3373,7 +3462,7 @@ public class JSONObjectTest {
public void issue654IncorrectNestingNoKey1() { public void issue654IncorrectNestingNoKey1() {
JSONObject json_input = new JSONObject("{{\"a\":0}}"); JSONObject json_input = new JSONObject("{{\"a\":0}}");
assertNotNull(json_input); assertNotNull(json_input);
fail("Excepected Exception."); fail("Expected Exception.");
} }
/** /**

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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.*; import java.util.*;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.*; import static org.junit.Assert.*;
@@ -78,7 +58,6 @@ public class Util {
* or something else. * or something else.
* @param value created by the code to be tested * @param value created by the code to be tested
* @param expectedValue created specifically for comparing * @param expectedValue created specifically for comparing
* @param key key to the jsonObject entry to be compared
*/ */
private static void compareActualVsExpectedObjects(Object value, private static void compareActualVsExpectedObjects(Object value,
Object expectedValue) { Object expectedValue) {
@@ -117,4 +96,106 @@ public class Util {
); );
} }
} }
/**
* Asserts that all JSONObject maps are the same as the default ctor
* @param jsonObjects list of objects to be tested
*/
public static void checkJSONObjectsMaps(List<JSONObject> jsonObjects) {
if (jsonObjects == null || jsonObjects.size() == 0) {
return;
}
Class<? extends Map> mapType = new JSONObject().getMapType();
for (JSONObject jsonObject : jsonObjects) {
if (jsonObject != null) {
assertTrue(mapType == jsonObject.getMapType());
checkJSONObjectMaps(jsonObject, mapType);
}
}
}
/**
* Asserts that all JSONObject maps are the same as the default ctor
* @param jsonObject the object to be tested
*/
public static void checkJSONObjectMaps(JSONObject jsonObject) {
if (jsonObject != null) {
checkJSONObjectMaps(jsonObject, jsonObject.getMapType());
}
}
/**
* Asserts that all JSONObject maps are the same as mapType
* @param jsonObject object to be tested
* @param mapType mapType to test against
*/
public static void checkJSONObjectMaps(JSONObject jsonObject, Class<? extends Map> mapType) {
if (mapType == null) {
mapType = new JSONObject().getMapType();
}
Set<String> keys = jsonObject.keySet();
for (String key : keys) {
Object val = jsonObject.get(key);
if (val instanceof JSONObject) {
JSONObject jsonObjectVal = (JSONObject) val;
assertTrue(mapType == ((JSONObject) val).getMapType());
checkJSONObjectMaps(jsonObjectVal, mapType);
} else if (val instanceof JSONArray) {
JSONArray jsonArrayVal = (JSONArray)val;
checkJSONArrayMaps(jsonArrayVal, mapType);
}
}
}
/**
* Asserts that all JSONObject maps in the JSONArray object match the default map
* @param jsonArrays list of JSONArray objects to be tested
*/
public static void checkJSONArraysMaps(List<JSONArray> jsonArrays) {
if (jsonArrays == null || jsonArrays.size() == 0) {
return;
}
Class<? extends Map> mapType = new JSONObject().getMapType();
for (JSONArray jsonArray : jsonArrays) {
if (jsonArray != null) {
checkJSONArrayMaps(jsonArray, mapType);
}
}
}
/**
* Asserts that all JSONObject maps in the JSONArray object match mapType
* @param jsonArray object to be tested
* @param mapType map type to be tested against
*/
public static void checkJSONArrayMaps(JSONArray jsonArray, Class<? extends Map> mapType) {
if (jsonArray == null) {
return;
}
if (mapType == null) {
mapType = new JSONObject().getMapType();
}
Iterator<Object> it = jsonArray.iterator();
while (it.hasNext()) {
Object val = it.next();
if (val instanceof JSONObject) {
JSONObject jsonObjectVal = (JSONObject)val;
checkJSONObjectMaps(jsonObjectVal, mapType);
} else if (val instanceof JSONArray) {
JSONArray jsonArrayVal = (JSONArray)val;
checkJSONArrayMaps(jsonArrayVal, mapType);
}
}
}
/**
* Asserts that all JSONObject maps nested in the JSONArray match
* the default mapType
* @param jsonArray the object to be tested
*/
public static void checkJSONArrayMaps(JSONArray jsonArray) {
if (jsonArray != null) {
checkJSONArrayMaps(jsonArray, null);
}
}
} }

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@@ -1,27 +1,7 @@
package org.json.junit; package org.json.junit;
/* /*
Copyright (c) 2020 JSON.org Public Domain.
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 org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;