Compare commits

...

8 Commits

Author SHA1 Message Date
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
9 changed files with 468 additions and 205 deletions

View File

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

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

View File

@@ -288,7 +288,7 @@ public class JSONArray implements Iterable<Object> {
.equalsIgnoreCase("true"))) {
return true;
}
throw wrongValueFormatException(index, "boolean", null);
throw wrongValueFormatException(index, "boolean", object, null);
}
/**
@@ -309,7 +309,7 @@ public class JSONArray implements Iterable<Object> {
try {
return Double.parseDouble(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(index, "double", e);
throw wrongValueFormatException(index, "double", object, e);
}
}
@@ -331,7 +331,7 @@ public class JSONArray implements Iterable<Object> {
try {
return Float.parseFloat(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(index, "float", e);
throw wrongValueFormatException(index, "float", object, e);
}
}
@@ -353,7 +353,7 @@ public class JSONArray implements Iterable<Object> {
}
return JSONObject.stringToNumber(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(index, "number", e);
throw wrongValueFormatException(index, "number", object, e);
}
}
@@ -378,7 +378,7 @@ public class JSONArray implements Iterable<Object> {
// If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException
throw wrongValueFormatException(index, "enum of type "
+ JSONObject.quote(clazz.getSimpleName()), null);
+ JSONObject.quote(clazz.getSimpleName()), opt(index), null);
}
return val;
}
@@ -441,7 +441,7 @@ public class JSONArray implements Iterable<Object> {
try {
return Integer.parseInt(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(index, "int", e);
throw wrongValueFormatException(index, "int", object, e);
}
}
@@ -460,7 +460,7 @@ public class JSONArray implements Iterable<Object> {
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw wrongValueFormatException(index, "JSONArray", null);
throw wrongValueFormatException(index, "JSONArray", object, null);
}
/**
@@ -478,7 +478,7 @@ public class JSONArray implements Iterable<Object> {
if (object instanceof JSONObject) {
return (JSONObject) object;
}
throw wrongValueFormatException(index, "JSONObject", null);
throw wrongValueFormatException(index, "JSONObject", object, null);
}
/**
@@ -499,7 +499,7 @@ public class JSONArray implements Iterable<Object> {
try {
return Long.parseLong(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(index, "long", e);
throw wrongValueFormatException(index, "long", object, e);
}
}
@@ -517,7 +517,7 @@ public class JSONArray implements Iterable<Object> {
if (object instanceof String) {
return (String) object;
}
throw wrongValueFormatException(index, "String", null);
throw wrongValueFormatException(index, "String", object, null);
}
/**
@@ -1464,6 +1464,7 @@ public class JSONArray implements Iterable<Object> {
* &nbsp;<small>(right bracket)</small>.
* @throws JSONException if a called function fails
*/
@SuppressWarnings("resource")
public String toString(int indentFactor) throws JSONException {
StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
@@ -1513,6 +1514,7 @@ public class JSONArray implements Iterable<Object> {
* @return The writer.
* @throws JSONException if a called function fails or unable to write
*/
@SuppressWarnings("resource")
public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
@@ -1680,22 +1682,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.
* @param idx index of the item
@@ -1708,8 +1694,19 @@ public class JSONArray implements Iterable<Object> {
String valueType,
Object value,
Throwable cause) {
if(value == null) {
return new JSONException(
"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 + ")."
"JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")."
, cause);
}

View File

@@ -166,6 +166,10 @@ public class JSONObject {
*/
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
* <code>NULL</code> object than to use Java's <code>null</code> value.
@@ -609,7 +613,7 @@ public class JSONObject {
// JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf
// 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;
}
@@ -635,7 +639,7 @@ public class JSONObject {
.equalsIgnoreCase("true"))) {
return true;
}
throw wrongValueFormatException(key, "Boolean", null);
throw wrongValueFormatException(key, "Boolean", object, null);
}
/**
@@ -697,7 +701,7 @@ public class JSONObject {
try {
return Double.parseDouble(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(key, "double", e);
throw wrongValueFormatException(key, "double", object, e);
}
}
@@ -719,7 +723,7 @@ public class JSONObject {
try {
return Float.parseFloat(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(key, "float", e);
throw wrongValueFormatException(key, "float", object, e);
}
}
@@ -741,7 +745,7 @@ public class JSONObject {
}
return stringToNumber(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(key, "number", e);
throw wrongValueFormatException(key, "number", object, e);
}
}
@@ -763,7 +767,7 @@ public class JSONObject {
try {
return Integer.parseInt(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(key, "int", e);
throw wrongValueFormatException(key, "int", object, e);
}
}
@@ -781,7 +785,7 @@ public class JSONObject {
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw wrongValueFormatException(key, "JSONArray", null);
throw wrongValueFormatException(key, "JSONArray", object, null);
}
/**
@@ -798,7 +802,7 @@ public class JSONObject {
if (object instanceof JSONObject) {
return (JSONObject) object;
}
throw wrongValueFormatException(key, "JSONObject", null);
throw wrongValueFormatException(key, "JSONObject", object, null);
}
/**
@@ -819,7 +823,7 @@ public class JSONObject {
try {
return Long.parseLong(object.toString());
} catch (Exception e) {
throw wrongValueFormatException(key, "long", e);
throw wrongValueFormatException(key, "long", object, e);
}
}
@@ -875,7 +879,7 @@ public class JSONObject {
if (object instanceof String) {
return (String) object;
}
throw wrongValueFormatException(key, "string", null);
throw wrongValueFormatException(key, "string", object, null);
}
/**
@@ -1201,12 +1205,11 @@ public class JSONObject {
}
if (exact) {
return new BigDecimal(((Number)val).doubleValue());
}else {
// 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
// intended representation
return new BigDecimal(val.toString());
}
// 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
// intended representation
return new BigDecimal(val.toString());
}
if (val instanceof Long || val instanceof Integer
|| val instanceof Short || val instanceof Byte){
@@ -2021,6 +2024,7 @@ public class JSONObject {
* A String
* @return A String correctly formatted for insertion in a JSON text.
*/
@SuppressWarnings("resource")
public static String quote(String string) {
StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
@@ -2141,7 +2145,7 @@ public class JSONObject {
} else if (valueThis instanceof Number && valueOther instanceof Number) {
if (!isNumberSimilar((Number)valueThis, (Number)valueOther)) {
return false;
};
}
} else if (!valueThis.equals(valueOther)) {
return false;
}
@@ -2409,6 +2413,7 @@ public class JSONObject {
* @throws JSONException
* If the object contains an invalid number.
*/
@SuppressWarnings("resource")
public String toString(int indentFactor) throws JSONException {
StringWriter w = new StringWriter();
synchronized (w.getBuffer()) {
@@ -2502,9 +2507,7 @@ public class JSONObject {
if (objectsRecord != null) {
return new JSONObject(object, objectsRecord);
}
else {
return new JSONObject(object);
}
return new JSONObject(object);
}
catch (JSONException exception) {
throw exception;
@@ -2527,6 +2530,7 @@ public class JSONObject {
return this.write(writer, 0, 0);
}
@SuppressWarnings("resource")
static final Writer writeValue(Writer writer, Object value,
int indentFactor, int indent) throws JSONException, IOException {
if (value == null || value.equals(null)) {
@@ -2604,6 +2608,7 @@ public class JSONObject {
* @throws JSONException if a called function has an error or a write error
* occurs
*/
@SuppressWarnings("resource")
public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
@@ -2686,22 +2691,6 @@ public class JSONObject {
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.
* @param key name of the key
@@ -2714,8 +2703,20 @@ public class JSONObject {
String valueType,
Object value,
Throwable cause) {
if(value == null) {
return new JSONException(
"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 + ")."
"JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")."
, cause);
}

View File

@@ -26,7 +26,6 @@ SOFTWARE.
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;

View File

@@ -237,6 +237,10 @@ public class JSONArrayTest {
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObj));
Util.checkJSONArrayMaps(expected);
Util.checkJSONArrayMaps(jaObj);
Util.checkJSONArrayMaps(jaRaw);
Util.checkJSONArrayMaps(jaInt);
}
/**
@@ -275,6 +279,7 @@ public class JSONArrayTest {
myList.get(i),
jsonArray.getString(myInts.length + i));
}
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -308,6 +313,9 @@ public class JSONArrayTest {
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaInt));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jaRaw, jaObj, jaInt
)));
}
@@ -351,6 +359,9 @@ public class JSONArrayTest {
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
expected, jaRaw, jaStrObj, jaStrInt, jaObjObj
)));
}
/**
@@ -397,6 +408,7 @@ public class JSONArrayTest {
new Long(-1).equals(jsonArray.getLong(12)));
assertTrue("Array value null", jsonArray.isNull(-1));
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -412,7 +424,7 @@ public class JSONArrayTest {
assertTrue("expected getBoolean to fail", false);
} catch (JSONException e) {
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 {
jsonArray.get(-1);
@@ -426,43 +438,44 @@ public class JSONArrayTest {
assertTrue("expected getDouble to fail", false);
} catch (JSONException e) {
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 {
jsonArray.getInt(4);
assertTrue("expected getInt to fail", false);
} catch (JSONException e) {
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 {
jsonArray.getJSONArray(4);
assertTrue("expected getJSONArray to fail", false);
} catch (JSONException e) {
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 {
jsonArray.getJSONObject(4);
assertTrue("expected getJSONObject to fail", false);
} catch (JSONException e) {
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 {
jsonArray.getLong(4);
assertTrue("expected getLong to fail", false);
} catch (JSONException e) {
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 {
jsonArray.getString(5);
assertTrue("expected getString to fail", false);
} catch (JSONException e) {
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 +512,7 @@ public class JSONArrayTest {
assertTrue("expected value4", "value4".equals(jsonArray.query("/10/key4")));
assertTrue("expected 0", Integer.valueOf(0).equals(jsonArray.query("/11")));
assertTrue("expected \"-1\"", "-1".equals(jsonArray.query("/12")));
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -512,6 +526,9 @@ public class JSONArrayTest {
assertTrue("expected JSONArray length 13. instead found "+jsonArray.length(), jsonArray.length() == 13);
JSONArray nestedJsonArray = jsonArray.getJSONArray(9);
assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1);
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jsonArray, nestedJsonArray
)));
}
/**
@@ -587,6 +604,10 @@ public class JSONArrayTest {
"hello".equals(jsonArray.optString(4)));
assertTrue("Array opt string default implicit",
"".equals(jsonArray.optString(-1)));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jsonArray, nestedJsonArray
)));
Util.checkJSONObjectMaps(nestedJsonObject);
}
/**
@@ -601,7 +622,9 @@ public class JSONArrayTest {
assertTrue("unexpected optLong value",ja.optLong(0,0)==123);
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 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
@@ -677,6 +700,8 @@ public class JSONArrayTest {
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 2", Integer.valueOf(2).equals(jsonArray.query("/9/1")));
Util.checkJSONArrayMaps(jsonArray);
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -756,6 +781,8 @@ public class JSONArrayTest {
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 v1", "v1".equals(jsonArray.query("/10/k1")));
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -772,6 +799,7 @@ public class JSONArrayTest {
jsonArray.remove(0);
assertTrue("array should be empty", null == jsonArray.remove(5));
assertTrue("jsonArray should be empty", jsonArray.isEmpty());
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -811,6 +839,12 @@ public class JSONArrayTest {
otherJsonArray.put("world");
assertTrue("arrays values differ",
!jsonArray.similar(otherJsonArray));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
jsonArray, otherJsonArray
)));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, otherJsonObject
)));
}
/**
@@ -894,6 +928,7 @@ public class JSONArrayTest {
for (String s : jsonArray4Strs) {
list.contains(s);
}
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -905,6 +940,9 @@ public class JSONArrayTest {
JSONArray jsonArray = new JSONArray();
assertTrue("toJSONObject should return null",
null == jsonArray.toJSONObject(names));
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
names, jsonArray
)));
}
/**
@@ -926,6 +964,7 @@ public class JSONArrayTest {
assertTrue("expected 5", Integer.valueOf(5).equals(jsonArray.query("/4")));
assertTrue("expected 6", Integer.valueOf(6).equals(jsonArray.query("/5")));
assertTrue("expected 7", Integer.valueOf(7).equals(jsonArray.query("/6")));
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -968,6 +1007,10 @@ public class JSONArrayTest {
assertTrue("Array value string long",
new Long(-1).equals(Long.parseLong((String) it.next())));
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)
@@ -1010,6 +1053,7 @@ public class JSONArrayTest {
} finally {
stringWriter.close();
}
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -1069,9 +1113,11 @@ public class JSONArrayTest {
&& actualStr.contains("\"key2\": false")
&& actualStr.contains("\"key3\": 3.14")
);
Util.checkJSONArrayMaps(finalArray);
} finally {
stringWriter.close();
}
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -1182,6 +1228,7 @@ public class JSONArrayTest {
// assert that the new list is mutable
assertTrue("Removing an entry should succeed", list.remove(2) != null);
assertTrue("List should have 2 elements", list.size() == 2);
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -1190,13 +1237,13 @@ public class JSONArrayTest {
*/
@Test
public void testJSONArrayInt() {
assertNotNull(new JSONArray(0));
assertNotNull(new JSONArray(5));
// 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.
assertEquals(0l, new JSONArray(10).length());
assertNotNull(new JSONArray(0));
assertNotNull(new JSONArray(5));
// 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.
// assertEquals(0l, new JSONArray(10).length());
try {
assertNotNull("Should throw an exception", new JSONArray(-1));
assertNotNull("Should throw an exception", new JSONArray(-1));
} catch (JSONException e) {
assertEquals("Expected an exception message",
"JSONArray initial capacity cannot be negative.",
@@ -1223,8 +1270,8 @@ public class JSONArrayTest {
((Collection<Object>)o).add("test");
((Collection<Object>)o).add(false);
try {
a = new JSONArray(o);
assertNull("Should error", a);
JSONArray a0 = new JSONArray(o);
assertNull("Should error", a0);
} catch (JSONException ex) {
}
@@ -1232,10 +1279,11 @@ public class JSONArrayTest {
// this is required for backwards compatibility
o = a;
try {
a = new JSONArray(o);
assertNull("Should error", a);
JSONArray a1 = new JSONArray(o);
assertNull("Should error", a1);
} catch (JSONException ex) {
}
Util.checkJSONArrayMaps(a);
}
/**
@@ -1252,6 +1300,9 @@ public class JSONArrayTest {
for(int i = 0; i < a1.length(); i++) {
assertEquals("index " + i + " are equal", a1.get(i), a2.get(i));
}
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
a1, a2
)));
}
/**
@@ -1269,6 +1320,9 @@ public class JSONArrayTest {
for(int i = 0; i < a1.length(); i++) {
assertEquals("index " + i + " are equal", a1.get(i), a2.get(i));
}
Util.checkJSONArraysMaps(new ArrayList<JSONArray>(Arrays.asList(
a1, a2
)));
}
/**
@@ -1284,6 +1338,7 @@ public class JSONArrayTest {
jsonArray.clear(); //Clears the JSONArray
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
Util.checkJSONArrayMaps(jsonArray);
}
/**
@@ -1297,5 +1352,6 @@ public class JSONArrayTest {
JSONArray json_input = new JSONArray(tokener);
assertNotNull(json_input);
fail("Excepected Exception.");
Util.checkJSONArrayMaps(json_input);
}
}

View File

@@ -158,7 +158,7 @@ public class JSONMLTest {
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"JSONArray[0] is not a String.",
"JSONArray[0] is not a String (class org.json.JSONArray).",
e.getMessage());
}
}

View File

@@ -41,14 +41,7 @@ import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
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.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
@@ -80,6 +73,7 @@ import org.json.junit.data.Singleton;
import org.json.junit.data.SingletonEnum;
import org.json.junit.data.WeirdList;
import org.junit.Test;
import org.json.junit.Util;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
@@ -140,8 +134,12 @@ public class JSONObjectTest {
JSONObject first = new JSONObject("{\"a\": 1, \"b\": 2, \"c\": 3}");
JSONObject second = new JSONObject("{\"a\": 1, \"b\": 2.0, \"c\": 4}");
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
public void timeNumberParsing() {
// test data to use
@@ -214,7 +212,9 @@ public class JSONObjectTest {
*/
@Test(expected=NullPointerException.class)
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 +232,7 @@ public class JSONObjectTest {
assertTrue("expected value1", textStr.contains("\"value1\""));
assertTrue("expected key2", textStr.contains("\"key2\""));
assertTrue("expected 42", textStr.contains("42"));
Util.checkJSONObjectMaps(jsonObject);
}
@Test
@@ -252,6 +253,7 @@ public class JSONObjectTest {
final String actualString = json.optString("key");
assert str.equals(actualString) : "Incorrect key value. Got "
+ actualString + " expected " + str;
Util.checkJSONObjectMaps(json);
}
/**
@@ -261,6 +263,7 @@ public class JSONObjectTest {
public void emptyJsonObject() {
JSONObject jsonObject = new JSONObject();
assertTrue("jsonObject should be empty", jsonObject.isEmpty());
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -291,6 +294,7 @@ public class JSONObjectTest {
assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey")));
assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey")));
assertTrue("expected \"doubleKey\":-23.45e67", new BigDecimal("-23.45e67").equals(jsonObjectByName.query("/doubleKey")));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(jsonObject, jsonObjectByName)));
}
/**
@@ -304,6 +308,7 @@ public class JSONObjectTest {
Map<String, Object> map = null;
JSONObject jsonObject = new JSONObject(map);
assertTrue("jsonObject should be empty", jsonObject.isEmpty());
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -329,6 +334,7 @@ public class JSONObjectTest {
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 \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -367,6 +373,9 @@ public class JSONObjectTest {
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(
Arrays.asList(jaRaw, jaStrObj, jaStrInt, jaObjObj))
);
}
/**
@@ -384,8 +393,8 @@ public class JSONObjectTest {
* The only getter is getNumber (key=number), whose return value is
* BigDecimal(42).
*/
JSONObject jsonObject = new JSONObject(new MyNumberContainer());
String actual = jsonObject.toString();
JSONObject jsonObject0 = new JSONObject(new MyNumberContainer());
String actual = jsonObject0.toString();
String expected = "{\"myNumber\":{\"number\":42}}";
assertEquals("Equal", expected , actual);
@@ -397,9 +406,9 @@ public class JSONObjectTest {
* The MyNumber.toString() method is responsible for
* returning a reasonable value: the string '42'.
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new MyNumber());
actual = jsonObject.toString();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("myNumber", new MyNumber());
actual = jsonObject1.toString();
expected = "{\"myNumber\":42}";
assertEquals("Equal", expected , actual);
@@ -411,8 +420,8 @@ public class JSONObjectTest {
* wrap() inserts the value as a string. That is why 42 comes back
* wrapped in quotes.
*/
jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42)));
actual = jsonObject.toString();
JSONObject jsonObject2 = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42)));
actual = jsonObject2.toString();
expected = "{\"myNumber\":\"42\"}";
assertEquals("Equal", expected , actual);
@@ -422,9 +431,9 @@ public class JSONObjectTest {
* AtomicInteger is recognized as a Number, and converted via
* numberToString() into the unquoted string '42'.
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new AtomicInteger(42));
actual = jsonObject.toString();
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("myNumber", new AtomicInteger(42));
actual = jsonObject3.toString();
expected = "{\"myNumber\":42}";
assertEquals("Equal", expected , actual);
@@ -435,11 +444,11 @@ public class JSONObjectTest {
* bean and inserted into a contained JSONObject. It has 2 getters,
* for numerator and denominator.
*/
jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2)));
assertEquals(1, jsonObject.length());
assertEquals(2, ((JSONObject)(jsonObject.get("myNumber"))).length());
assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator"));
assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator"));
JSONObject jsonObject4 = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2)));
assertEquals(1, jsonObject4.length());
assertEquals(2, ((JSONObject)(jsonObject4.get("myNumber"))).length());
assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject4.query("/myNumber/numerator"));
assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject4.query("/myNumber/denominator"));
/**
* JSONObject.put() inserts the Fraction directly into the
@@ -449,11 +458,15 @@ public class JSONObjectTest {
* BigDecimal sanity check fails, so writeValue() defaults
* to returning a safe JSON quoted string. Pretty slick!
*/
jsonObject = new JSONObject();
jsonObject.put("myNumber", new Fraction(4,2));
actual = jsonObject.toString();
JSONObject jsonObject5 = new JSONObject();
jsonObject5.put("myNumber", new Fraction(4,2));
actual = jsonObject5.toString();
expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed
assertEquals("Equal", expected , actual);
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject0, jsonObject1, jsonObject2, jsonObject3, jsonObject4, jsonObject5
)));
}
/**
@@ -488,6 +501,10 @@ public class JSONObjectTest {
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaInt));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jaRaw, jaObj, jaInt
)));
}
@@ -531,6 +548,10 @@ public class JSONObjectTest {
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jaRaw, jaStrObj, jaStrInt, jaStrObj
)));
}
@@ -553,6 +574,7 @@ public class JSONObjectTest {
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 \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -580,6 +602,7 @@ public class JSONObjectTest {
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 \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -620,6 +643,7 @@ public class JSONObjectTest {
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 callbacks[1] items", ((Map<?,?>)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0);
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -655,6 +679,7 @@ public class JSONObjectTest {
// InterfaceField replaces someFloat property name via user-defined annotation
assertTrue("Overridden String field name (InterfaceField) should have been found",
jsonObject.has("InterfaceField"));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -705,6 +730,7 @@ public class JSONObjectTest {
// property name able was replaced by Getable via user-defined annotation
assertTrue("Overridden boolean field name (Getable) should have been found",
jsonObject.has("Getable"));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -725,6 +751,7 @@ public class JSONObjectTest {
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString")));
assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -746,6 +773,7 @@ public class JSONObjectTest {
assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2);
assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later")));
assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -778,6 +806,7 @@ public class JSONObjectTest {
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 -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -809,6 +838,7 @@ public class JSONObjectTest {
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 -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -944,6 +974,7 @@ public class JSONObjectTest {
JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey");
assertTrue("objectKey should be JSONObject",
jsonObjectInner.get("myKey").equals("myVal"));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -1006,6 +1037,7 @@ public class JSONObjectTest {
obj = jsonObject.get( "largeExponent" );
assertTrue("largeExponent should evaluate as a BigDecimal",
new BigDecimal("-23.45e2327").equals(obj));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -1054,6 +1086,7 @@ public class JSONObjectTest {
jsonObject.get("floatIdentifier").equals(Double.valueOf(0.1)));
assertTrue("doubleIdentifier currently evaluates to double 0.1",
jsonObject.get("doubleIdentifier").equals(Double.valueOf(0.1)));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -1090,7 +1123,7 @@ public class JSONObjectTest {
fail("Expected an exception");
} catch (JSONException e) {
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());
}
try {
@@ -1106,7 +1139,7 @@ public class JSONObjectTest {
fail("Expected an exception");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"JSONObject[\"trueKey\"] is not a string.",
"JSONObject[\"trueKey\"] is not a string (class java.lang.Boolean : true).",
e.getMessage());
}
try {
@@ -1122,7 +1155,7 @@ public class JSONObjectTest {
fail("Expected an exception");
} catch (JSONException e) {
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());
}
try {
@@ -1138,7 +1171,7 @@ public class JSONObjectTest {
fail("Expected an exception");
} catch (JSONException e) {
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());
}
try {
@@ -1154,7 +1187,7 @@ public class JSONObjectTest {
fail("Expected an exception");
} catch (JSONException e) {
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());
}
try {
@@ -1170,7 +1203,7 @@ public class JSONObjectTest {
fail("Expected an exception");
} catch (JSONException e) {
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());
}
try {
@@ -1186,7 +1219,7 @@ public class JSONObjectTest {
fail("Expected an exception");
} catch (JSONException e) {
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());
}
try {
@@ -1202,9 +1235,10 @@ public class JSONObjectTest {
fail("Expected an exception");
} catch (JSONException e) {
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());
}
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -1232,6 +1266,7 @@ public class JSONObjectTest {
assertTrue("3.0 can still be interpreted as a double",
deserialized.getDouble(key30) == 3.0);
assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1);
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -1247,9 +1282,9 @@ public class JSONObjectTest {
* value is stored. This should be fixed.
*/
BigInteger bigInteger = new BigInteger("123456789012345678901234567890");
JSONObject jsonObject = new JSONObject(bigInteger);
Object obj = jsonObject.get("lowestSetBit");
assertTrue("JSONObject only has 1 value", jsonObject.length() == 1);
JSONObject jsonObject0 = new JSONObject(bigInteger);
Object obj = jsonObject0.get("lowestSetBit");
assertTrue("JSONObject only has 1 value", jsonObject0.length() == 1);
assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet",
obj instanceof Integer);
assertTrue("this bigInteger lowestBitSet happens to be 1",
@@ -1262,57 +1297,57 @@ public class JSONObjectTest {
*/
BigDecimal bigDecimal = new BigDecimal(
"123456789012345678901234567890.12345678901234567890123456789");
jsonObject = new JSONObject(bigDecimal);
assertTrue("large bigDecimal is not stored", jsonObject.isEmpty());
JSONObject jsonObject1 = new JSONObject(bigDecimal);
assertTrue("large bigDecimal is not stored", jsonObject1.isEmpty());
/**
* JSONObject put(String, Object) method stores and serializes
* bigInt and bigDec correctly. Nothing needs to change.
*/
jsonObject = new JSONObject();
jsonObject.put("bigInt", bigInteger);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("bigInt", bigInteger);
assertTrue("jsonObject.put() handles bigInt correctly",
jsonObject.get("bigInt").equals(bigInteger));
jsonObject2.get("bigInt").equals(bigInteger));
assertTrue("jsonObject.getBigInteger() handles bigInt correctly",
jsonObject.getBigInteger("bigInt").equals(bigInteger));
jsonObject2.getBigInteger("bigInt").equals(bigInteger));
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",
jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}"));
jsonObject2.toString().equals("{\"bigInt\":123456789012345678901234567890}"));
assertTrue("BigInteger as BigDecimal",
jsonObject.getBigDecimal("bigInt").equals(new BigDecimal(bigInteger)));
jsonObject2.getBigDecimal("bigInt").equals(new BigDecimal(bigInteger)));
jsonObject = new JSONObject();
jsonObject.put("bigDec", bigDecimal);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("bigDec", bigDecimal);
assertTrue("jsonObject.put() handles bigDec correctly",
jsonObject.get("bigDec").equals(bigDecimal));
jsonObject3.get("bigDec").equals(bigDecimal));
assertTrue("jsonObject.getBigDecimal() handles bigDec correctly",
jsonObject.getBigDecimal("bigDec").equals(bigDecimal));
jsonObject3.getBigDecimal("bigDec").equals(bigDecimal));
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",
jsonObject.toString().equals(
jsonObject3.toString().equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
assertTrue("BigDecimal as BigInteger",
jsonObject.getBigInteger("bigDec").equals(bigDecimal.toBigInteger()));
jsonObject3.getBigInteger("bigDec").equals(bigDecimal.toBigInteger()));
/**
* exercise some exceptions
*/
try {
// bigInt key does not exist
jsonObject.getBigDecimal("bigInt");
jsonObject3.getBigDecimal("bigInt");
fail("expected an exeption");
} catch (JSONException ignored) {}
obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE);
obj = jsonObject3.optBigDecimal("bigInt", BigDecimal.ONE);
assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE));
jsonObject.put("stringKey", "abc");
jsonObject3.put("stringKey", "abc");
try {
jsonObject.getBigDecimal("stringKey");
jsonObject3.getBigDecimal("stringKey");
fail("expected an exeption");
} catch (JSONException ignored) {}
obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE);
obj = jsonObject3.optBigInteger("bigDec", BigInteger.ONE);
assertTrue("expected BigInteger", obj instanceof BigInteger);
assertEquals(bigDecimal.toBigInteger(), obj);
@@ -1345,79 +1380,79 @@ public class JSONObjectTest {
// bigInt map ctor
Map<String, Object> map = new HashMap<String, Object>();
map.put("bigInt", bigInteger);
jsonObject = new JSONObject(map);
String actualFromMapStr = jsonObject.toString();
JSONObject jsonObject4 = new JSONObject(map);
String actualFromMapStr = jsonObject4.toString();
assertTrue("bigInt in map (or array or bean) is a string",
actualFromMapStr.equals(
"{\"bigInt\":123456789012345678901234567890}"));
// bigInt put
jsonObject = new JSONObject();
jsonObject.put("bigInt", bigInteger);
String actualFromPutStr = jsonObject.toString();
JSONObject jsonObject5 = new JSONObject();
jsonObject5.put("bigInt", bigInteger);
String actualFromPutStr = jsonObject5.toString();
assertTrue("bigInt from put is a number",
actualFromPutStr.equals(
"{\"bigInt\":123456789012345678901234567890}"));
// bigDec map ctor
map = new HashMap<String, Object>();
map.put("bigDec", bigDecimal);
jsonObject = new JSONObject(map);
actualFromMapStr = jsonObject.toString();
JSONObject jsonObject6 = new JSONObject(map);
actualFromMapStr = jsonObject6.toString();
assertTrue("bigDec in map (or array or bean) is a bigDec",
actualFromMapStr.equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
// bigDec put
jsonObject = new JSONObject();
jsonObject.put("bigDec", bigDecimal);
actualFromPutStr = jsonObject.toString();
JSONObject jsonObject7 = new JSONObject();
jsonObject7.put("bigDec", bigDecimal);
actualFromPutStr = jsonObject7.toString();
assertTrue("bigDec from put is a number",
actualFromPutStr.equals(
"{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}"));
// bigInt,bigDec put
JSONArray jsonArray = new JSONArray();
jsonArray.put(bigInteger);
jsonArray.put(bigDecimal);
actualFromPutStr = jsonArray.toString();
JSONArray jsonArray0 = new JSONArray();
jsonArray0.put(bigInteger);
jsonArray0.put(bigDecimal);
actualFromPutStr = jsonArray0.toString();
assertTrue("bigInt, bigDec from put is a number",
actualFromPutStr.equals(
"[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]"));
assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger));
assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal));
assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger));
assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal));
jsonArray.put(Boolean.TRUE);
assertTrue("getBigInt is bigInt", jsonArray0.getBigInteger(0).equals(bigInteger));
assertTrue("getBigDec is bigDec", jsonArray0.getBigDecimal(1).equals(bigDecimal));
assertTrue("optBigInt is bigInt", jsonArray0.optBigInteger(0, BigInteger.ONE).equals(bigInteger));
assertTrue("optBigDec is bigDec", jsonArray0.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal));
jsonArray0.put(Boolean.TRUE);
try {
jsonArray.getBigInteger(2);
jsonArray0.getBigInteger(2);
fail("should not be able to get big int");
} catch (Exception ignored) {}
try {
jsonArray.getBigDecimal(2);
jsonArray0.getBigDecimal(2);
fail("should not be able to get big dec");
} catch (Exception ignored) {}
assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE));
assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE));
assertTrue("optBigInt is default", jsonArray0.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE));
assertTrue("optBigDec is default", jsonArray0.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE));
// bigInt,bigDec list ctor
List<Object> list = new ArrayList<Object>();
list.add(bigInteger);
list.add(bigDecimal);
jsonArray = new JSONArray(list);
String actualFromListStr = jsonArray.toString();
JSONArray jsonArray1 = new JSONArray(list);
String actualFromListStr = jsonArray1.toString();
assertTrue("bigInt, bigDec in list is a bigInt, bigDec",
actualFromListStr.equals(
"[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]"));
// bigInt bean ctor
MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class);
when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890"));
jsonObject = new JSONObject(myBigNumberBean);
String actualFromBeanStr = jsonObject.toString();
JSONObject jsonObject8 = new JSONObject(myBigNumberBean);
String actualFromBeanStr = jsonObject8.toString();
// can't do a full string compare because mockery adds an extra key/value
assertTrue("bigInt from bean ctor is a bigInt",
actualFromBeanStr.contains("123456789012345678901234567890"));
// bigDec bean ctor
myBigNumberBean = mock(MyBigNumberBean.class);
when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789"));
jsonObject = new JSONObject(myBigNumberBean);
actualFromBeanStr = jsonObject.toString();
jsonObject8 = new JSONObject(myBigNumberBean);
actualFromBeanStr = jsonObject8.toString();
// can't do a full string compare because mockery adds an extra key/value
assertTrue("bigDec from bean ctor is a bigDec",
actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789"));
@@ -1426,7 +1461,12 @@ public class JSONObjectTest {
assertTrue("wrap() returns big num",obj.equals(bigInteger));
obj = JSONObject.wrap(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 +1478,6 @@ public class JSONObjectTest {
*/
@Test
public void jsonObjectNames() {
JSONObject jsonObject;
// getNames() from null JSONObject
assertTrue("null names from null Object",
@@ -1449,16 +1488,16 @@ public class JSONObjectTest {
null == JSONObject.getNames(new MyJsonString()));
// getNames from new JSONOjbect
jsonObject = new JSONObject();
String [] names = JSONObject.getNames(jsonObject);
JSONObject jsonObject0 = new JSONObject();
String [] names = JSONObject.getNames(jsonObject0);
assertTrue("names should be null", names == null);
// getNames() from empty JSONObject
String emptyStr = "{}";
jsonObject = new JSONObject(emptyStr);
JSONObject jsonObject1 = new JSONObject(emptyStr);
assertTrue("empty JSONObject should have null names",
null == JSONObject.getNames(jsonObject));
null == JSONObject.getNames(jsonObject1));
// getNames() from JSONObject
String str =
@@ -1467,13 +1506,13 @@ public class JSONObjectTest {
"\"falseKey\":false,"+
"\"stringKey\":\"hello world!\","+
"}";
jsonObject = new JSONObject(str);
names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = new JSONArray(names);
JSONObject jsonObject2 = new JSONObject(str);
names = JSONObject.getNames(jsonObject2);
JSONArray jsonArray0 = new JSONArray(names);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString());
.parse(jsonArray0.toString());
List<?> docList = JsonPath.read(doc, "$");
assertTrue("expected 3 items", docList.size() == 3);
assertTrue(
@@ -1494,9 +1533,9 @@ public class JSONObjectTest {
names = JSONObject.getNames(myEnumField);
// validate JSON
jsonArray = new JSONArray(names);
JSONArray jsonArray1 = new JSONArray(names);
doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString());
.parse(jsonArray1.toString());
docList = JsonPath.read(doc, "$");
assertTrue("expected 3 items", docList.size() == 3);
assertTrue(
@@ -1518,9 +1557,9 @@ public class JSONObjectTest {
names = JSONObject.getNames(myPublicClass);
// validate JSON
jsonArray = new JSONArray(names);
JSONArray jsonArray2 = new JSONArray(names);
doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonArray.toString());
.parse(jsonArray2.toString());
docList = JsonPath.read(doc, "$");
assertTrue("expected 2 items", docList.size() == 2);
assertTrue(
@@ -1529,6 +1568,12 @@ public class JSONObjectTest {
assertTrue(
"expected to find publicInt",
((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 +1585,8 @@ public class JSONObjectTest {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.names();
assertTrue("jsonArray should be null", jsonArray == null);
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType());
}
/**
@@ -1564,6 +1611,8 @@ public class JSONObjectTest {
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 stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1);
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType());
}
/**
@@ -1682,7 +1731,9 @@ public class JSONObjectTest {
// 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
// really in the scope of a JSON-library (IMHO.)
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, inc
)));
}
/**
@@ -1780,6 +1831,12 @@ public class JSONObjectTest {
JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr);
assertTrue("different nested JSONArrays should not be similar",
!aCompareArrayJsonObject.similar(bCompareArrayJsonObject));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, expectedJsonObject, aCompareValueJsonObject,
aCompareArrayJsonObject, aCompareObjectJsonObject, aCompareArrayJsonObject,
bCompareValueJsonObject, bCompareArrayJsonObject, bCompareObjectJsonObject,
bCompareArrayJsonObject
)));
}
/**
@@ -1815,6 +1872,7 @@ public class JSONObjectTest {
assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2")));
assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3")));
assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -1888,6 +1946,9 @@ public class JSONObjectTest {
JSONObject jo = new JSONObject().put("TABLE", new JSONObject().put("yhoo", new JSONObject()));
assertEquals("toString(2)","{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObject, jo
)));
}
/**
@@ -1909,6 +1970,7 @@ public class JSONObjectTest {
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 def", "def".equals(jsonObject.query("/key/abc")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -1931,6 +1993,7 @@ public class JSONObjectTest {
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 abc", "abc".equals(jsonObject.query("/key/0")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -1978,7 +2041,9 @@ public class JSONObjectTest {
jsonArray.toString().equals(JSONObject.valueToString(collection)));
Integer[] array = { new Integer(1), new Integer(2), new Integer(3) };
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 +2147,11 @@ public class JSONObjectTest {
assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1")));
assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2")));
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 +2166,7 @@ public class JSONObjectTest {
try {
JSONObject jo = new JSONObject(source);
assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key")));
Util.checkJSONObjectMaps(jo);
} 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",
i=='\0' || i=='\n' || i=='\r'
@@ -2395,6 +2466,7 @@ public class JSONObjectTest {
assertTrue("jsonObject should be empty", jsonObject.isEmpty());
jsonObject.putOnce(null, "");
assertTrue("jsonObject should be empty", jsonObject.isEmpty());
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -2430,6 +2502,7 @@ public class JSONObjectTest {
42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue());
assertTrue("optString() should return default string",
"hi".equals(jsonObject.optString("hiKey", "hi")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -2466,6 +2539,7 @@ public class JSONObjectTest {
42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue());
assertTrue("optString() should return default string",
"hi".equals(jsonObject.optString("hiKey", "hi")));
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -2484,6 +2558,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 optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l);
Util.checkJSONObjectMaps(jo);
}
/**
@@ -2518,6 +2593,7 @@ public class JSONObjectTest {
assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumberStr"));
assertEquals(19007199254740992l, (long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"));
assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"));
Util.checkJSONObjectMaps(jo);
}
/**
@@ -2540,6 +2616,7 @@ public class JSONObjectTest {
assertNull(jo.optBigDecimal("nullVal", null));
assertEquals(jo.optBigDecimal("float", null),jo.getBigDecimal("float"));
assertEquals(jo.optBigDecimal("double", null),jo.getBigDecimal("double"));
Util.checkJSONObjectMaps(jo);
}
/**
@@ -2560,6 +2637,7 @@ public class JSONObjectTest {
assertEquals(new BigInteger("1234"),jo.optBigInteger("bigInteger", null));
assertEquals(new BigInteger("1234"),jo.optBigInteger("bigDecimal", null));
assertNull(jo.optBigDecimal("nullVal", null));
Util.checkJSONObjectMaps(jo);
}
/**
@@ -2577,8 +2655,9 @@ public class JSONObjectTest {
JSONObject jsonObjectPutNull = new JSONObject(str);
jsonObjectPutNull.put("myKey", (Object) null);
assertTrue("jsonObject should be empty", jsonObjectPutNull.isEmpty());
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObjectRemove, jsonObjectPutNull
)));
}
/**
@@ -2663,6 +2742,7 @@ public class JSONObjectTest {
} finally {
stringWriter.close();
}
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -2745,7 +2825,7 @@ public class JSONObjectTest {
writer.close();
} catch (Exception e) {}
}
Util.checkJSONObjectMaps(jsonObject);
}
@@ -2813,6 +2893,7 @@ public class JSONObjectTest {
stringWriter.close();
} catch (Exception e) {}
}
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -2855,6 +2936,7 @@ public class JSONObjectTest {
JSONObject aJsonObject = new JSONObject(str);
assertTrue("Same JSONObject should be equal to itself",
aJsonObject.equals(aJsonObject));
Util.checkJSONObjectMaps(aJsonObject);
}
/**
@@ -2940,6 +3022,9 @@ public class JSONObjectTest {
"<key>null</key>".equals(sJONull));
String sNull = XML.toString(jsonObjectNull);
assertTrue("null should emit an empty string", "".equals(sNull));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jsonObjectJONull, jsonObjectNull
)));
}
@Test(expected = JSONPointerException.class)
@@ -3037,6 +3122,7 @@ public class JSONObjectTest {
// assert that the new map is mutable
assertTrue("Removing a key should succeed", map.remove("key3") != null);
assertTrue("Map should have 2 elements", map.size() == 2);
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -3061,6 +3147,9 @@ public class JSONObjectTest {
// ensure our original jo hasn't changed.
assertEquals(0, jo.get("someInt"));
assertEquals(null, jo.opt("someString"));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jo, jo2
)));
}
/**
@@ -3085,6 +3174,9 @@ public class JSONObjectTest {
// ensure our original jo hasn't changed.
assertEquals(0, jo.get("someInt"));
assertEquals(null, jo.opt("someString"));
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
jo, jo2
)));
}
/**
@@ -3100,6 +3192,7 @@ public class JSONObjectTest {
assertEquals("Expected the getter to only be called once",
1, bean.genericGetCounter);
assertEquals(0, bean.genericSetCounter);
Util.checkJSONObjectMaps(jo);
}
/**
@@ -3115,6 +3208,7 @@ public class JSONObjectTest {
assertEquals("Expected the getter to only be called once",
1, bean.genericGetCounter);
assertEquals(0, bean.genericSetCounter);
Util.checkJSONObjectMaps(jo);
}
/**
@@ -3133,6 +3227,7 @@ public class JSONObjectTest {
assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(),
1, jo.length());
assertNotNull(jo.get("ALL"));
Util.checkJSONObjectMaps(jo);
}
/**
@@ -3150,6 +3245,8 @@ public class JSONObjectTest {
BigDecimal wantedValue = BigDecimal.valueOf(value);
assertEquals(current, wantedValue);
Util.checkJSONObjectMaps(jsonObject);
Util.checkJSONArrayMaps(array, jsonObject.getMapType());
}
/**
@@ -3163,6 +3260,7 @@ public class JSONObjectTest {
1, jo.length());
assertTrue(jo.get("closeable") instanceof JSONObject);
assertTrue(jo.getJSONObject("closeable").has("string"));
Util.checkJSONObjectMaps(jo);
}
@Test(expected=NullPointerException.class)
@@ -3289,9 +3387,12 @@ public class JSONObjectTest {
ObjC.setRef(ObjA);
ObjB.setRef(ObjA);
ObjB.setRef2(ObjA);
new JSONObject(ObjC);
new JSONObject(ObjB);
new JSONObject(ObjA);
JSONObject j0 = new JSONObject(ObjC);
JSONObject j1 = new JSONObject(ObjB);
JSONObject j2 = new JSONObject(ObjA);
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
j0, j1, j2
)));
}
@Test
public void testLongRepeatObjectNotRecursive() {
@@ -3307,17 +3408,21 @@ public class JSONObjectTest {
ObjB.setRef2(ObjD);
ObjA.setRef(ObjD);
ObjD.setRef(ObjE);
new JSONObject(ObjC);
new JSONObject(ObjB);
new JSONObject(ObjA);
new JSONObject(ObjD);
new JSONObject(ObjE);
JSONObject j0 = new JSONObject(ObjC);
JSONObject j1 = new JSONObject(ObjB);
JSONObject j2 = new JSONObject(ObjA);
JSONObject j3 = new JSONObject(ObjD);
JSONObject j4 = new JSONObject(ObjE);
Util.checkJSONObjectsMaps(new ArrayList<JSONObject>(Arrays.asList(
j0, j1, j2, j3, j4
)));
}
@Test(expected=JSONException.class)
public void testRecursiveEquals() {
RecursiveBeanEquals a = new RecursiveBeanEquals("same");
a.setRef(a);
new JSONObject(a);
JSONObject j0 = new JSONObject(a);
Util.checkJSONObjectMaps(j0);
}
@Test
public void testNotRecursiveEquals() {
@@ -3326,7 +3431,8 @@ public class JSONObjectTest {
RecursiveBeanEquals c = new RecursiveBeanEquals("same");
a.setRef(b);
b.setRef(c);
new JSONObject(a);
JSONObject j0 = new JSONObject(a);
Util.checkJSONObjectMaps(j0);
}
@@ -3336,6 +3442,7 @@ public class JSONObjectTest {
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"));
assertEquals("'empty_json_array' should have a length of 0", 0, jsonObject.getJSONArray("empty_json_array").length());
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -3351,6 +3458,7 @@ public class JSONObjectTest {
jsonObject.clear(); //Clears the JSONObject
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
Util.checkJSONObjectMaps(jsonObject);
}
/**
@@ -3364,6 +3472,7 @@ public class JSONObjectTest {
JSONObject json_input = new JSONObject(input);
assertNotNull(json_input);
fail("Excepected Exception.");
Util.checkJSONObjectMaps(json_input);
}
/**
@@ -3373,7 +3482,7 @@ public class JSONObjectTest {
public void issue654IncorrectNestingNoKey1() {
JSONObject json_input = new JSONObject("{{\"a\":0}}");
assertNotNull(json_input);
fail("Excepected Exception.");
fail("Expected Exception.");
}
/**

View File

@@ -78,7 +78,6 @@ public class Util {
* or something else.
* @param value created by the code to be tested
* @param expectedValue created specifically for comparing
* @param key key to the jsonObject entry to be compared
*/
private static void compareActualVsExpectedObjects(Object value,
Object expectedValue) {
@@ -117,4 +116,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);
}
}
}