1
0
Fork 0
mirror of https://github.com/ethauvin/JSON-java.git synced 2025-06-17 07:50:52 -07:00

* Update link in the README to the main JSON-Java repo

* Cleans up some warnings
* Adds new test for bug https://github.com/stleary/JSON-java/issues/332
* Adds some resource handling for string writers using pre-java1.7
support. I know StringWriters don't need a close method called, but the
tests should still handle their resources properly.
This commit is contained in:
John J. Aylward 2017-04-27 12:39:42 -04:00
parent f6ab6d7b27
commit 9df5d34bbe
10 changed files with 2878 additions and 2703 deletions

View file

@ -2,7 +2,7 @@
Unit tests to validate the JSON-Java GitHub project code<br> Unit tests to validate the JSON-Java GitHub project code<br>
https://github.com/douglascrockford/JSON-java<br> https://github.com/stleary/JSON-java<br>
Gradle and Eclipse is the recommended build tool and IDE.<br> Gradle and Eclipse is the recommended build tool and IDE.<br>
Run individual tests or <b>JunitTestSuite</b> using <b>EclEmma Coverage</b>, or execute the **TestRunner** application directly.<br> Run individual tests or <b>JunitTestSuite</b> using <b>EclEmma Coverage</b>, or execute the **TestRunner** application directly.<br>

View file

@ -5,7 +5,6 @@ import static org.junit.Assert.assertTrue;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -92,7 +91,7 @@ public class EnumTest {
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1"))); assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1")));
assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2"))); assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2")));
assertTrue("expected VAL3", myEnumField.VAL3.equals(jsonObject.query("/VAL3"))); assertTrue("expected VAL3", MyEnumField.VAL3.equals(jsonObject.query("/VAL3")));
} }
/** /**

View file

@ -1,11 +1,11 @@
package org.json.junit; package org.json.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.ArrayList; import java.util.ArrayList;
@ -61,7 +61,7 @@ public class JSONArrayTest {
@Test(expected=NullPointerException.class) @Test(expected=NullPointerException.class)
public void nullException() { public void nullException() {
String str = null; String str = null;
new JSONArray(str); assertNull("Should throw an exception", new JSONArray(str));
} }
/** /**
@ -72,8 +72,7 @@ public class JSONArrayTest {
public void emptStr() { public void emptStr() {
String str = ""; String str = "";
try { try {
new JSONArray(str); assertNull("Should throw an exception", new JSONArray(str));
assertTrue("Should throw an exception", false);
} catch (JSONException e) { } catch (JSONException e) {
assertTrue("Expected an exception message", assertTrue("Expected an exception message",
"A JSONArray text must start with '[' at 1 [character 2 line 1]". "A JSONArray text must start with '[' at 1 [character 2 line 1]".
@ -90,8 +89,7 @@ public class JSONArrayTest {
public void badObject() { public void badObject() {
String str = "abc"; String str = "abc";
try { try {
new JSONArray((Object)str); assertNull("Should throw an exception", new JSONArray((Object)str));
assertTrue("Should throw an exception", false);
} catch (JSONException e) { } catch (JSONException e) {
assertTrue("Expected an exception message", assertTrue("Expected an exception message",
"JSONArray initial value should be a string or collection or array.". "JSONArray initial value should be a string or collection or array.".
@ -100,7 +98,7 @@ public class JSONArrayTest {
} }
/** /**
* Verifies that the constructor has backwards compatability with RAW types pre-java5. * Verifies that the constructor has backwards compatibility with RAW types pre-java5.
*/ */
@Test @Test
public void verifyConstructor() { public void verifyConstructor() {
@ -130,7 +128,7 @@ public class JSONArrayTest {
} }
/** /**
* Verifies that the put Collection has backwards compatability with RAW types pre-java5. * Verifies that the put Collection has backwards compatibility with RAW types pre-java5.
*/ */
@Test @Test
public void verifyPutCollection() { public void verifyPutCollection() {
@ -164,7 +162,7 @@ public class JSONArrayTest {
/** /**
* Verifies that the put Map has backwards compatability with RAW types pre-java5. * Verifies that the put Map has backwards compatibility with RAW types pre-java5.
*/ */
@Test @Test
public void verifyPutMap() { public void verifyPutMap() {
@ -209,9 +207,10 @@ public class JSONArrayTest {
* Create a JSONArray doc with a variety of different elements. * Create a JSONArray doc with a variety of different elements.
* Confirm that the values can be accessed via the get[type]() API methods * Confirm that the values can be accessed via the get[type]() API methods
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void getArrayValues() { public void getArrayValues() {
JSONArray jsonArray = new JSONArray(arrayStr); JSONArray jsonArray = new JSONArray(this.arrayStr);
// booleans // booleans
assertTrue("Array true", assertTrue("Array true",
true == jsonArray.getBoolean(0)); true == jsonArray.getBoolean(0));
@ -255,7 +254,7 @@ public class JSONArrayTest {
*/ */
@Test @Test
public void failedGetArrayValues() { public void failedGetArrayValues() {
JSONArray jsonArray = new JSONArray(arrayStr); JSONArray jsonArray = new JSONArray(this.arrayStr);
try { try {
jsonArray.getBoolean(4); jsonArray.getBoolean(4);
assertTrue("expected getBoolean to fail", false); assertTrue("expected getBoolean to fail", false);
@ -321,7 +320,7 @@ public class JSONArrayTest {
*/ */
@Test @Test
public void join() { public void join() {
JSONArray jsonArray = new JSONArray(arrayStr); JSONArray jsonArray = new JSONArray(this.arrayStr);
String joinStr = jsonArray.join(","); String joinStr = jsonArray.join(",");
// validate JSON // validate JSON
@ -357,7 +356,7 @@ public class JSONArrayTest {
public void length() { public void length() {
assertTrue("expected empty JSONArray length 0", assertTrue("expected empty JSONArray length 0",
new JSONArray().length() == 0); new JSONArray().length() == 0);
JSONArray jsonArray = new JSONArray(arrayStr); JSONArray jsonArray = new JSONArray(this.arrayStr);
assertTrue("expected JSONArray length 13", jsonArray.length() == 13); assertTrue("expected JSONArray length 13", 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);
@ -368,9 +367,10 @@ public class JSONArrayTest {
* Confirm that the values can be accessed via the opt[type](index) * Confirm that the values can be accessed via the opt[type](index)
* and opt[type](index, default) API methods. * and opt[type](index, default) API methods.
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void opt() { public void opt() {
JSONArray jsonArray = new JSONArray(arrayStr); JSONArray jsonArray = new JSONArray(this.arrayStr);
assertTrue("Array opt value true", assertTrue("Array opt value true",
Boolean.TRUE == jsonArray.opt(0)); Boolean.TRUE == jsonArray.opt(0));
assertTrue("Array opt value out of range", assertTrue("Array opt value out of range",
@ -441,6 +441,7 @@ public class JSONArrayTest {
* Exercise the JSONArray.put(value) method with various parameters * Exercise the JSONArray.put(value) method with various parameters
* and confirm the resulting JSONArray. * and confirm the resulting JSONArray.
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void put() { public void put() {
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
@ -516,6 +517,7 @@ public class JSONArrayTest {
* Exercise the JSONArray.put(index, value) method with various parameters * Exercise the JSONArray.put(index, value) method with various parameters
* and confirm the resulting JSONArray. * and confirm the resulting JSONArray.
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void putIndex() { public void putIndex() {
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
@ -596,11 +598,11 @@ public class JSONArrayTest {
*/ */
@Test @Test
public void remove() { public void remove() {
String arrayStr = String arrayStr1 =
"["+ "["+
"1"+ "1"+
"]"; "]";
JSONArray jsonArray = new JSONArray(arrayStr); JSONArray jsonArray = new JSONArray(arrayStr1);
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.length() == 0); assertTrue("jsonArray should be empty", jsonArray.length() == 0);
@ -612,11 +614,11 @@ public class JSONArrayTest {
*/ */
@Test @Test
public void notSimilar() { public void notSimilar() {
String arrayStr = String arrayStr1 =
"["+ "["+
"1"+ "1"+
"]"; "]";
JSONArray jsonArray = new JSONArray(arrayStr); JSONArray jsonArray = new JSONArray(arrayStr1);
JSONArray otherJsonArray = new JSONArray(); JSONArray otherJsonArray = new JSONArray();
assertTrue("arrays lengths differ", !jsonArray.similar(otherJsonArray)); assertTrue("arrays lengths differ", !jsonArray.similar(otherJsonArray));
@ -745,9 +747,10 @@ public class JSONArrayTest {
/** /**
* Exercise the JSONArray iterator. * Exercise the JSONArray iterator.
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void iterator() { public void iterator() {
JSONArray jsonArray = new JSONArray(arrayStr); JSONArray jsonArray = new JSONArray(this.arrayStr);
Iterator<Object> it = jsonArray.iterator(); Iterator<Object> it = jsonArray.iterator();
assertTrue("Array true", assertTrue("Array true",
Boolean.TRUE.equals(it.next())); Boolean.TRUE.equals(it.next()));
@ -803,16 +806,20 @@ public class JSONArrayTest {
* Exercise the JSONArray write() method * Exercise the JSONArray write() method
*/ */
@Test @Test
public void write() { public void write() throws IOException {
String str = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":2,\"key3\":3}]"; String str = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":2,\"key3\":3}]";
JSONArray jsonArray = new JSONArray(str); JSONArray jsonArray = new JSONArray(str);
String expectedStr = str; String expectedStr = str;
StringWriter stringWriter = new StringWriter(); StringWriter stringWriter = new StringWriter();
Writer writer = jsonArray.write(stringWriter); try {
String actualStr = writer.toString(); jsonArray.write(stringWriter);
assertTrue("write() expected " + expectedStr + String actualStr = stringWriter.toString();
" but found " + actualStr, assertTrue("write() expected " + expectedStr +
expectedStr.equals(actualStr)); " but found " + actualStr,
expectedStr.equals(actualStr));
} finally {
stringWriter.close();
}
} }
/** /**
@ -837,7 +844,7 @@ public class JSONArrayTest {
* Exercise the JSONArray write(Writer, int, int) method * Exercise the JSONArray write(Writer, int, int) method
*/ */
@Test @Test
public void write3Param() { public void write3Param() throws IOException {
String str0 = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":false,\"key3\":3.14}]"; String str0 = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":false,\"key3\":3.14}]";
String str2 = String str2 =
"[\n" + "[\n" +
@ -852,15 +859,20 @@ public class JSONArrayTest {
JSONArray jsonArray = new JSONArray(str0); JSONArray jsonArray = new JSONArray(str0);
String expectedStr = str0; String expectedStr = str0;
StringWriter stringWriter = new StringWriter(); StringWriter stringWriter = new StringWriter();
Writer writer = jsonArray.write(stringWriter, 0, 0); try {
String actualStr = writer.toString(); String actualStr = jsonArray.write(stringWriter, 0, 0).toString();
assertEquals(expectedStr, actualStr); assertEquals(expectedStr, actualStr);
} finally {
expectedStr = str2; stringWriter.close();
}
stringWriter = new StringWriter(); stringWriter = new StringWriter();
writer = jsonArray.write(stringWriter, 2, 1); try {
actualStr = writer.toString(); expectedStr = str2;
assertEquals(expectedStr, actualStr); String actualStr = jsonArray.write(stringWriter, 2, 1).toString();
assertEquals(expectedStr, actualStr);
} finally {
stringWriter.close();
}
} }
/** /**
@ -917,49 +929,49 @@ public class JSONArrayTest {
"]"; "]";
JSONArray jsonArray = new JSONArray(jsonArrayStr); JSONArray jsonArray = new JSONArray(jsonArrayStr);
List list = jsonArray.toList(); List<?> list = jsonArray.toList();
assertTrue("List should not be null", list != null); assertTrue("List should not be null", list != null);
assertTrue("List should have 3 elements", list.size() == 3); assertTrue("List should have 3 elements", list.size() == 3);
List val1List = (List) list.get(0); List<?> val1List = (List<?>) list.get(0);
assertTrue("val1 should not be null", val1List != null); assertTrue("val1 should not be null", val1List != null);
assertTrue("val1 should have 3 elements", val1List.size() == 3); assertTrue("val1 should have 3 elements", val1List.size() == 3);
assertTrue("val1 value 1 should be 1", val1List.get(0).equals(Integer.valueOf(1))); assertTrue("val1 value 1 should be 1", val1List.get(0).equals(Integer.valueOf(1)));
assertTrue("val1 value 2 should be 2", val1List.get(1).equals(Integer.valueOf(2))); assertTrue("val1 value 2 should be 2", val1List.get(1).equals(Integer.valueOf(2)));
Map key1Value3Map = (Map)val1List.get(2); Map<?,?> key1Value3Map = (Map<?,?>)val1List.get(2);
assertTrue("Map should not be null", key1Value3Map != null); assertTrue("Map should not be null", key1Value3Map != null);
assertTrue("Map should have 1 element", key1Value3Map.size() == 1); assertTrue("Map should have 1 element", key1Value3Map.size() == 1);
assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE));
Map val2Map = (Map) list.get(1); Map<?,?> val2Map = (Map<?,?>) list.get(1);
assertTrue("val2 should not be null", val2Map != null); assertTrue("val2 should not be null", val2Map != null);
assertTrue("val2 should have 4 elements", val2Map.size() == 4); assertTrue("val2 should have 4 elements", val2Map.size() == 4);
assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1")); assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1"));
assertTrue("val2 map key 3 should be 42", val2Map.get("key3").equals(Integer.valueOf(42))); assertTrue("val2 map key 3 should be 42", val2Map.get("key3").equals(Integer.valueOf(42)));
Map val2Key2Map = (Map)val2Map.get("key2"); Map<?,?> val2Key2Map = (Map<?,?>)val2Map.get("key2");
assertTrue("val2 map key 2 should not be null", val2Key2Map != null); assertTrue("val2 map key 2 should not be null", val2Key2Map != null);
assertTrue("val2 map key 2 should have an entry", val2Key2Map.containsKey("key2")); assertTrue("val2 map key 2 should have an entry", val2Key2Map.containsKey("key2"));
assertTrue("val2 map key 2 value should be null", val2Key2Map.get("key2") == null); assertTrue("val2 map key 2 value should be null", val2Key2Map.get("key2") == null);
List val2Key4List = (List)val2Map.get("key4"); List<?> val2Key4List = (List<?>)val2Map.get("key4");
assertTrue("val2 map key 4 should not be null", val2Key4List != null); assertTrue("val2 map key 4 should not be null", val2Key4List != null);
assertTrue("val2 map key 4 should be empty", val2Key4List.isEmpty()); assertTrue("val2 map key 4 should be empty", val2Key4List.isEmpty());
List val3List = (List) list.get(2); List<?> val3List = (List<?>) list.get(2);
assertTrue("val3 should not be null", val3List != null); assertTrue("val3 should not be null", val3List != null);
assertTrue("val3 should have 2 elements", val3List.size() == 2); assertTrue("val3 should have 2 elements", val3List.size() == 2);
List val3Val1List = (List)val3List.get(0); List<?> val3Val1List = (List<?>)val3List.get(0);
assertTrue("val3 list val 1 should not be null", val3Val1List != null); assertTrue("val3 list val 1 should not be null", val3Val1List != null);
assertTrue("val3 list val 1 should have 2 elements", val3Val1List.size() == 2); assertTrue("val3 list val 1 should have 2 elements", val3Val1List.size() == 2);
assertTrue("val3 list val 1 list element 1 should be value1", val3Val1List.get(0).equals("value1")); assertTrue("val3 list val 1 list element 1 should be value1", val3Val1List.get(0).equals("value1"));
assertTrue("val3 list val 1 list element 2 should be 2.1", val3Val1List.get(1).equals(Double.valueOf("2.1"))); assertTrue("val3 list val 1 list element 2 should be 2.1", val3Val1List.get(1).equals(Double.valueOf("2.1")));
List val3Val2List = (List)val3List.get(1); List<?> val3Val2List = (List<?>)val3List.get(1);
assertTrue("val3 list val 2 should not be null", val3Val2List != null); assertTrue("val3 list val 2 should not be null", val3Val2List != null);
assertTrue("val3 list val 2 should have 1 element", val3Val2List.size() == 1); assertTrue("val3 list val 2 should have 1 element", val3Val2List.size() == 1);
assertTrue("val3 list val 2 list element 1 should be null", val3Val2List.get(0) == null); assertTrue("val3 list val 2 list element 1 should be null", val3Val2List.get(0) == null);

View file

@ -711,8 +711,7 @@ public class JSONMLTest {
} }
/** /**
* JSON string cannot be reverted to original xml. See test result in * JSON string cannot be reverted to original xml when type guessing is used.
* comment below.
*/ */
@Test @Test
public void testToJSONArray_reversibility() { public void testToJSONArray_reversibility() {
@ -722,10 +721,11 @@ public class JSONMLTest {
} }
/** /**
* test passes when using the new method toJsonML. * JSON string cannot be reverted to original xml when type guessing is used.
* When we force all the values as string, the original text comes back.
*/ */
@Test @Test
public void testToJsonML() { public void testToJSONArray_reversibility2() {
final String originalXml = "<root><id>01</id><id>1</id><id>00</id><id>0</id><item id=\"01\"/><title>True</title></root>"; final String originalXml = "<root><id>01</id><id>1</id><id>00</id><id>0</id><item id=\"01\"/><title>True</title></root>";
final String expectedJsonString = "[\"root\",[\"id\",\"01\"],[\"id\",\"1\"],[\"id\",\"00\"],[\"id\",\"0\"],[\"item\",{\"id\":\"01\"}],[\"title\",\"True\"]]"; final String expectedJsonString = "[\"root\",[\"id\",\"01\"],[\"id\",\"1\"],[\"id\",\"00\"],[\"id\",\"0\"],[\"item\",{\"id\":\"01\"}],[\"title\",\"True\"]]";
final JSONArray json = JSONML.toJSONArray(originalXml,true); final JSONArray json = JSONML.toJSONArray(originalXml,true);
@ -735,4 +735,71 @@ public class JSONMLTest {
assertEquals(originalXml, reverseXml); assertEquals(originalXml, reverseXml);
} }
/**
* JSON can be reverted to original xml.
*/
@Test
public void testToJSONArray_reversibility3() {
final String originalXml = "<readResult><errors someAttr=\"arrtValue\"><code>400</code></errors><errors><code>402</code></errors></readResult>";
final JSONArray jsonArray = JSONML.toJSONArray(originalXml, false);
final String revertedXml = JSONML.toString(jsonArray);
assertEquals(revertedXml, originalXml);
}
/**
* JSON string cannot be reverted to original xml. See test result in
* comment below.
*/
@Test
public void testToJSONObject_reversibility() {
final String originalXml = "<readResult><errors someAttr=\"arrtValue\"><code>400</code></errors><errors><code>402</code></errors></readResult>";
final JSONObject originalObject=JSONML.toJSONObject(originalXml,false);
final String originalJson = originalObject.toString();
final String xml = JSONML.toString(originalObject);
final JSONObject revertedObject = JSONML.toJSONObject(xml, false);
final String newJson = revertedObject.toString();
assertTrue("JSON Objects are not similar",originalObject.similar(revertedObject));
assertEquals("original JSON does not equal the new JSON",originalJson, newJson);
}
/**
* Test texts taken from jsonml.org. Currently our implementation FAILS this conversion but shouldn't.
* Technically JsonML should be able to transform any valid xhtml document, but ours only supports
* standard XML entities, not HTML entities.
*/
@Test
public void testAttributeConversionReversabilityHTML() {
final String originalXml = "<table class=\"MyTable\" style=\"background-color:yellow\"><tr><td class=\"MyTD\" style=\"border:1px solid black\">#5D28D1</td><td class=\"MyTD\" style=\"background-color:red\">Example text here</td></tr><tr><td class=\"MyTD\" style=\"border:1px solid black\">#AF44EF</td><td class=\"MyTD\" style=\"background-color:green\">127310656</td></tr><tr><td class=\"MyTD\" style=\"border:1px solid black\">#AAD034</td><td class=\"MyTD\" style=\"background-color:blue\">&nbsp;<span style=\"background-color:maroon\">&copy;</span>&nbsp;</td></tr></table>";
final String expectedJsonString = "[\"table\",{\"class\" : \"MyTable\",\"style\" : \"background-color:yellow\"},[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#550758\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:red\"},\"Example text here\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#993101\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:green\"},\"127624015\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#E33D87\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:blue\"},\"\u00A0\",[\"span\",{ \"style\" : \"background-color:maroon\" },\"\u00A9\"],\"\u00A0\"]]]";
final JSONArray json = JSONML.toJSONArray(originalXml,true);
final String actualJsonString = json.toString();
final String reverseXml = JSONML.toString(json);
assertNotEquals(originalXml, reverseXml);
assertNotEquals(expectedJsonString, actualJsonString);
}
// this test does not pass for the following reasons:
// 1. Our XML parser does not handle generic HTML entities, only valid XML entities. Hence &nbsp;
// or other HTML specific entites would fail on reversability
// 2. Our JSON implementation for storing the XML attributes uses the standard unordered map.
// This means that <tag attr1="v1" attr2="v2" /> can not be reversed reliably.
// /**
// * Test texts taken from jsonml.org but modified to have XML entities only.
// */
// @Test
// public void testAttributeConversionReversabilityXML() {
// final String originalXml = "<table class=\"MyTable\" style=\"background-color:yellow\"><tr><td class=\"MyTD\" style=\"border:1px solid black\">#5D28D1</td><td class=\"MyTD\" style=\"background-color:red\">Example text here</td></tr><tr><td class=\"MyTD\" style=\"border:1px solid black\">#AF44EF</td><td class=\"MyTD\" style=\"background-color:green\">127310656</td></tr><tr><td class=\"MyTD\" style=\"border:1px solid black\">#AAD034</td><td class=\"MyTD\" style=\"background-color:blue\">&amp;<span style=\"background-color:maroon\">&gt;</span>&lt;</td></tr></table>";
// final String expectedJsonString = "[\"table\",{\"class\" : \"MyTable\",\"style\" : \"background-color:yellow\"},[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#550758\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:red\"},\"Example text here\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#993101\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:green\"},\"127624015\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#E33D87\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:blue\"},\"&\",[\"span\",{ \"style\" : \"background-color:maroon\" },\">\"],\"<\"]]]";
// final JSONArray jsonML = JSONML.toJSONArray(originalXml,true);
// final String actualJsonString = jsonML.toString();
//
// final String reverseXml = JSONML.toString(jsonML);
// // currently not equal because the hashing of the attribute objects makes the attribute
// // order not happen the same way twice
// assertEquals(originalXml, reverseXml);
//
// assertEquals(expectedJsonString, actualJsonString);
// }
} }

View file

@ -7,9 +7,9 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.ArrayList; import java.util.ArrayList;
@ -47,8 +47,7 @@ public class JSONObjectTest {
*/ */
@Test(expected=NullPointerException.class) @Test(expected=NullPointerException.class)
public void jsonObjectByNullBean() { public void jsonObjectByNullBean() {
MyBean myBean = null; assertNull("Expected an exception",new JSONObject((MyBean)null));
new JSONObject(myBean);
} }
/** /**
@ -68,6 +67,26 @@ public class JSONObjectTest {
assertTrue("expected 42", textStr.contains("42")); assertTrue("expected 42", textStr.contains("42"));
} }
@Test
public void testLongFromString(){
String str = "26315000000253009";
JSONObject json = new JSONObject();
json.put("key", str);
final Object actualKey = json.opt("key");
assert str.equals(actualKey) : "Incorrect key value. Got " + actualKey
+ " expected " + str;
final long actualLong = json.optLong("key");
assert actualLong != 0 : "Unable to extract long value for string " + str;
assert 26315000000253009L == actualLong : "Incorrect key value. Got "
+ actualLong + " expected " + str;
final String actualString = json.optString("key");
assert str.equals(actualString) : "Incorrect key value. Got "
+ actualString + " expected " + str;
}
/** /**
* A JSONObject can be created with no content * A JSONObject can be created with no content
*/ */
@ -245,7 +264,7 @@ public class JSONObjectTest {
/** /**
* Calls the JSONObject(Map) ctor, which calls wrap() for values. * Calls the JSONObject(Map) ctor, which calls wrap() for values.
* Fraction is a Number, but is not recognized by wrap(), per * Fraction is a Number, but is not recognized by wrap(), per
* current implementation. As a POJO, Franction is handled as a * current implementation. As a POJO, Fraction is handled as a
* 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.
*/ */
@ -271,7 +290,7 @@ public class JSONObjectTest {
} }
/** /**
* Verifies that the put Collection has backwards compatability with RAW types pre-java5. * Verifies that the put Collection has backwards compatibility with RAW types pre-java5.
*/ */
@Test @Test
public void verifyPutCollection() { public void verifyPutCollection() {
@ -400,6 +419,7 @@ public class JSONObjectTest {
* JSONObject built from a bean. In this case all but one of the * JSONObject built from a bean. In this case all but one of the
* bean getters return valid JSON types * bean getters return valid JSON types
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void jsonObjectByBean() { public void jsonObjectByBean() {
/** /**
@ -479,6 +499,7 @@ public class JSONObjectTest {
/** /**
* Exercise the JSONObject.accumulate() method * Exercise the JSONObject.accumulate() method
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void jsonObjectAccumulate() { public void jsonObjectAccumulate() {
@ -510,6 +531,7 @@ public class JSONObjectTest {
/** /**
* Exercise the JSONObject append() functionality * Exercise the JSONObject append() functionality
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void jsonObjectAppend() { public void jsonObjectAppend() {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
@ -540,6 +562,7 @@ public class JSONObjectTest {
/** /**
* Exercise the JSONObject doubleToString() method * Exercise the JSONObject doubleToString() method
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void jsonObjectDoubleToString() { public void jsonObjectDoubleToString() {
String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" };
@ -906,6 +929,7 @@ public class JSONObjectTest {
* Document behaviors of big numbers. Includes both JSONObject * Document behaviors of big numbers. Includes both JSONObject
* and JSONArray tests * and JSONArray tests
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void bigNumberOperations() { public void bigNumberOperations() {
/** /**
@ -1232,6 +1256,7 @@ public class JSONObjectTest {
/** /**
* Exercise the JSONObject increment() method. * Exercise the JSONObject increment() method.
*/ */
@SuppressWarnings("cast")
@Test @Test
public void jsonObjectIncrement() { public void jsonObjectIncrement() {
String str = String str =
@ -1285,7 +1310,7 @@ public class JSONObjectTest {
* http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1, * http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1,
* that decimal number (base10 representation) is periodic in base2 * that decimal number (base10 representation) is periodic in base2
* representation, therefore appending zero-bits is inaccurate. Only * representation, therefore appending zero-bits is inaccurate. Only
* repeating the periodically occuring bits (0110) would be a proper * repeating the periodically occurring bits (0110) would be a proper
* conversion. However one cannot detect from a 32 bit IEE754 * conversion. However one cannot detect from a 32 bit IEE754
* representation which bits would "repeat infinitely", since the * representation which bits would "repeat infinitely", since the
* missing bits would not fit into the 32 bit float, i.e. the * missing bits would not fit into the 32 bit float, i.e. the
@ -1350,6 +1375,7 @@ public class JSONObjectTest {
/** /**
* Exercise JSONObject numberToString() method * Exercise JSONObject numberToString() method
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void jsonObjectNumberToString() { public void jsonObjectNumberToString() {
String str; String str;
@ -1372,6 +1398,7 @@ public class JSONObjectTest {
/** /**
* Exercise JSONObject put() and similar() methods * Exercise JSONObject put() and similar() methods
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void jsonObjectPut() { public void jsonObjectPut() {
String expectedStr = String expectedStr =
@ -1641,6 +1668,7 @@ public class JSONObjectTest {
* The following code was throwing a ClassCastException in the * The following code was throwing a ClassCastException in the
* JSONObject(Map<String, Object>) constructor * JSONObject(Map<String, Object>) constructor
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void valueToStringConfirmException() { public void valueToStringConfirmException() {
Map<Integer, String> myMap = new HashMap<Integer, String>(); Map<Integer, String> myMap = new HashMap<Integer, String>();
@ -1672,7 +1700,7 @@ public class JSONObjectTest {
/** /**
* This test is to document the preferred behavior if BigDecimal is * This test is to document the preferred behavior if BigDecimal is
* supported. Previously bd returned as a string, since it * supported. Previously bd returned as a string, since it
* is recognized as being a Java package class. Now with explicit * is recognized as being a Java package class. Now with explicit
* support for big numbers, it remains a BigDecimal * support for big numbers, it remains a BigDecimal
*/ */
@ -1761,13 +1789,13 @@ public class JSONObjectTest {
/** /**
* Explore how JSONObject handles parsing errors. * Explore how JSONObject handles parsing errors.
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void jsonObjectParsingErrors() { public void jsonObjectParsingErrors() {
try { try {
// does not start with '{' // does not start with '{'
String str = "abc"; String str = "abc";
new JSONObject(str); assertNull("Expected an exception",new JSONObject(str));
assertTrue("Expected an exception", false);
} catch (JSONException e) { } catch (JSONException e) {
assertTrue("Expecting an exception message", assertTrue("Expecting an exception message",
"A JSONObject text must begin with '{' at 1 [character 2 line 1]". "A JSONObject text must begin with '{' at 1 [character 2 line 1]".
@ -1776,8 +1804,7 @@ public class JSONObjectTest {
try { try {
// does not end with '}' // does not end with '}'
String str = "{"; String str = "{";
new JSONObject(str); assertNull("Expected an exception",new JSONObject(str));
assertTrue("Expected an exception", false);
} catch (JSONException e) { } catch (JSONException e) {
assertTrue("Expecting an exception message", assertTrue("Expecting an exception message",
"A JSONObject text must end with '}' at 2 [character 3 line 1]". "A JSONObject text must end with '}' at 2 [character 3 line 1]".
@ -1786,8 +1813,7 @@ public class JSONObjectTest {
try { try {
// key with no ':' // key with no ':'
String str = "{\"myKey\" = true}"; String str = "{\"myKey\" = true}";
new JSONObject(str); assertNull("Expected an exception",new JSONObject(str));
assertTrue("Expected an exception", false);
} catch (JSONException e) { } catch (JSONException e) {
assertTrue("Expecting an exception message", assertTrue("Expecting an exception message",
"Expected a ':' after a key at 10 [character 11 line 1]". "Expected a ':' after a key at 10 [character 11 line 1]".
@ -1796,8 +1822,7 @@ public class JSONObjectTest {
try { try {
// entries with no ',' separator // entries with no ',' separator
String str = "{\"myKey\":true \"myOtherKey\":false}"; String str = "{\"myKey\":true \"myOtherKey\":false}";
new JSONObject(str); assertNull("Expected an exception",new JSONObject(str));
assertTrue("Expected an exception", false);
} catch (JSONException e) { } catch (JSONException e) {
assertTrue("Expecting an exception message", assertTrue("Expecting an exception message",
"Expected a ',' or '}' at 15 [character 16 line 1]". "Expected a ',' or '}' at 15 [character 16 line 1]".
@ -2051,16 +2076,19 @@ public class JSONObjectTest {
* Exercise the JSONObject write() method * Exercise the JSONObject write() method
*/ */
@Test @Test
public void write() { public void write() throws IOException {
String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}"; String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}";
String expectedStr = str; String expectedStr = str;
JSONObject jsonObject = new JSONObject(str); JSONObject jsonObject = new JSONObject(str);
StringWriter stringWriter = new StringWriter(); StringWriter stringWriter = new StringWriter();
Writer writer = jsonObject.write(stringWriter); try {
String actualStr = writer.toString(); String actualStr = jsonObject.write(stringWriter).toString();
assertTrue("write() expected " +expectedStr+ assertTrue("write() expected " +expectedStr+
" but found " +actualStr, " but found " +actualStr,
expectedStr.equals(actualStr)); expectedStr.equals(actualStr));
} finally {
stringWriter.close();
}
} }
/** /**
@ -2085,7 +2113,7 @@ public class JSONObjectTest {
* Exercise the JSONObject write(Writer, int, int) method * Exercise the JSONObject write(Writer, int, int) method
*/ */
@Test @Test
public void write3Param() { public void write3Param() throws IOException {
String str0 = "{\"key1\":\"value1\",\"key2\":[1,false,3.14]}"; String str0 = "{\"key1\":\"value1\",\"key2\":[1,false,3.14]}";
String str2 = String str2 =
"{\n" + "{\n" +
@ -2099,15 +2127,21 @@ public class JSONObjectTest {
JSONObject jsonObject = new JSONObject(str0); JSONObject jsonObject = new JSONObject(str0);
String expectedStr = str0; String expectedStr = str0;
StringWriter stringWriter = new StringWriter(); StringWriter stringWriter = new StringWriter();
Writer writer = jsonObject.write(stringWriter,0,0); try {
String actualStr = writer.toString(); String actualStr = jsonObject.write(stringWriter,0,0).toString();
assertEquals(expectedStr, actualStr); assertEquals(expectedStr, actualStr);
} finally {
stringWriter.close();
}
expectedStr = str2; expectedStr = str2;
stringWriter = new StringWriter(); stringWriter = new StringWriter();
writer = jsonObject.write(stringWriter,2,1); try {
actualStr = writer.toString(); String actualStr = jsonObject.write(stringWriter,2,1).toString();
assertEquals(expectedStr, actualStr); assertEquals(expectedStr, actualStr);
} finally {
stringWriter.close();
}
} }
/** /**
@ -2210,12 +2244,13 @@ public class JSONObjectTest {
obj = null; obj = null;
jsonObjectNull.put("key", obj); jsonObjectNull.put("key", obj);
value = jsonObjectNull.opt("key"); value = jsonObjectNull.opt("key");
assertTrue("opt() null should find null", value == null); assertNull("opt() null should find null", value);
if (value == null) { // what is this trying to do? It appears to test absolutely nothing...
value = ""; // if (value == null) {
} // value = "";
string = value instanceof String ? (String)value : null; // }
assertTrue("should convert null to empty string", "".equals(string)); // string = value instanceof String ? (String)value : null;
// assertTrue("should convert null to empty string", "".equals(string));
try { try {
value = jsonObjectNull.get("key"); value = jsonObjectNull.get("key");
assertTrue("get() null should throw exception", false); assertTrue("get() null should throw exception", false);
@ -2254,7 +2289,7 @@ public class JSONObjectTest {
@Test(expected = JSONException.class) @Test(expected = JSONException.class)
public void invalidEscapeSequence() { public void invalidEscapeSequence() {
String json = "{ \"\\url\": \"value\" }"; String json = "{ \"\\url\": \"value\" }";
new JSONObject(json); assertNull("Expected an exception",new JSONObject(json));
} }
/** /**

View file

@ -2,6 +2,7 @@ package org.json.junit;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.*; import java.util.*;
@ -26,65 +27,105 @@ public class JSONStringTest {
jsonArray.put((Object)null); jsonArray.put((Object)null);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
String output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[null]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[null]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
jsonArray.put(JSONObject.NULL); jsonArray.put(JSONObject.NULL);
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[null]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[null]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
jsonArray.put(new JSONObject()); jsonArray.put(new JSONObject());
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[{}]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[{}]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
jsonArray.put(new JSONArray()); jsonArray.put(new JSONArray());
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[[]]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[[]]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
Map singleMap = Collections.singletonMap("key1", "value1"); Map<?,?> singleMap = Collections.singletonMap("key1", "value1");
jsonArray.put((Object)singleMap); jsonArray.put((Object)singleMap);
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[{\"key1\":\"value1\"}]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[{\"key1\":\"value1\"}]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
List singleList = Collections.singletonList("entry1"); List<?> singleList = Collections.singletonList("entry1");
jsonArray.put((Object)singleList); jsonArray.put((Object)singleList);
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[[\"entry1\"]]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[[\"entry1\"]]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
int[] intArray = new int[] { 1, 2, 3 }; int[] intArray = new int[] { 1, 2, 3 };
jsonArray.put(intArray); jsonArray.put(intArray);
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[[1,2,3]]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[[1,2,3]]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
jsonArray.put(24); jsonArray.put(24);
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[24]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[24]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
jsonArray.put("string value"); jsonArray.put("string value");
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[\"string value\"]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[\"string value\"]".equals(output));
jsonArray = new JSONArray(); jsonArray = new JSONArray();
jsonArray.put(true); jsonArray.put(true);
} finally {
writer.close();
}
writer = new StringWriter(); writer = new StringWriter();
output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[true]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[true]".equals(output));
} finally {
writer.close();
}
} }
@ -92,6 +133,7 @@ public class JSONStringTest {
* This tests the JSONObject.valueToString() method. These should be * This tests the JSONObject.valueToString() method. These should be
* identical to the values above, except for the enclosing [ and ]. * identical to the values above, except for the enclosing [ and ].
*/ */
@SuppressWarnings("boxing")
@Test @Test
public void valuesToString() throws Exception { public void valuesToString() throws Exception {
@ -107,11 +149,11 @@ public class JSONStringTest {
output = JSONObject.valueToString(new JSONArray()); output = JSONObject.valueToString(new JSONArray());
assertTrue("String values should be equal", "[]".equals(output)); assertTrue("String values should be equal", "[]".equals(output));
Map singleMap = Collections.singletonMap("key1", "value1"); Map<?,?> singleMap = Collections.singletonMap("key1", "value1");
output = JSONObject.valueToString(singleMap); output = JSONObject.valueToString(singleMap);
assertTrue("String values should be equal", "{\"key1\":\"value1\"}".equals(output)); assertTrue("String values should be equal", "{\"key1\":\"value1\"}".equals(output));
List singleList = Collections.singletonList("entry1"); List<?> singleList = Collections.singletonList("entry1");
output = JSONObject.valueToString(singleList); output = JSONObject.valueToString(singleList);
assertTrue("String values should be equal", "[\"entry1\"]".equals(output)); assertTrue("String values should be equal", "[\"entry1\"]".equals(output));
@ -142,11 +184,15 @@ public class JSONStringTest {
jsonArray.put(jsonString); jsonArray.put(jsonString);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
String output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[\"the JSON string value\"]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[\"the JSON string value\"]".equals(output));
output = JSONObject.valueToString(jsonString); output = JSONObject.valueToString(jsonString);
assertTrue("String values should be equal", "\"the JSON string value\"".equals(output)); assertTrue("String values should be equal", "\"the JSON string value\"".equals(output));
} finally {
writer.close();
}
} }
/** /**
@ -161,17 +207,21 @@ public class JSONStringTest {
jsonArray.put(jsonString); jsonArray.put(jsonString);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[\"the toString value\"]".equals(output));
// The only different between writeValue() and valueToString():
// in this case, valueToString throws a JSONException
try { try {
output = JSONObject.valueToString(jsonString); String output = jsonArray.write(writer).toString();
fail("Expected an exception, got a String value"); assertTrue("String values should be equal", "[\"the toString value\"]".equals(output));
} catch (Exception e) {
assertTrue("Expected JSONException", e instanceof JSONException); // The only different between writeValue() and valueToString():
assertTrue("Exception message does not match", "Bad value from toJSONString: null".equals(e.getMessage())); // in this case, valueToString throws a JSONException
try {
output = JSONObject.valueToString(jsonString);
fail("Expected an exception, got a String value");
} catch (Exception e) {
assertTrue("Expected JSONException", e instanceof JSONException);
assertTrue("Exception message does not match", "Bad value from toJSONString: null".equals(e.getMessage()));
}
} finally {
writer.close();
} }
} }
@ -181,28 +231,31 @@ public class JSONStringTest {
* the original exception. * the original exception.
*/ */
@Test @Test
public void testJSONStringExceptionValue() throws Exception { public void testJSONStringExceptionValue() throws IOException {
JSONStringExceptionValue jsonString = new JSONStringExceptionValue(); JSONStringExceptionValue jsonString = new JSONStringExceptionValue();
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonString); jsonArray.put(jsonString);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
String output = null;
try { try {
output = jsonArray.write(writer).toString(); jsonArray.write(writer).toString();
fail("Expected an exception, got a String value"); fail("Expected an exception, got a String value");
} catch (Exception e) { } catch (JSONException e) {
assertTrue("Expected JSONException", e instanceof JSONException);
assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); assertTrue("Exception message does not match", "the exception value".equals(e.getMessage()));
} catch(Exception e) {
fail("Expected JSONException");
} finally {
writer.close();
} }
try { try {
output = JSONObject.valueToString(jsonString); JSONObject.valueToString(jsonString);
fail("Expected an exception, got a String value"); fail("Expected an exception, got a String value");
} catch (Exception e) { } catch (JSONException e) {
assertTrue("Expected JSONException", e instanceof JSONException);
assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); assertTrue("Exception message does not match", "the exception value".equals(e.getMessage()));
} catch(Exception e) {
fail("Expected JSONException");
} }
} }
@ -218,11 +271,15 @@ public class JSONStringTest {
jsonArray.put(nonJsonString); jsonArray.put(nonJsonString);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
String output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[\"the toString value for StringValue\"]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[\"the toString value for StringValue\"]".equals(output));
output = JSONObject.valueToString(nonJsonString); output = JSONObject.valueToString(nonJsonString);
assertTrue("String values should be equal", "\"the toString value for StringValue\"".equals(output)); assertTrue("String values should be equal", "\"the toString value for StringValue\"".equals(output));
} finally {
writer.close();
}
} }
/** /**
@ -237,11 +294,15 @@ public class JSONStringTest {
jsonArray.put(nonJsonString); jsonArray.put(nonJsonString);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
String output = jsonArray.write(writer).toString(); try {
assertTrue("String values should be equal", "[\"\"]".equals(output)); String output = jsonArray.write(writer).toString();
assertTrue("String values should be equal", "[\"\"]".equals(output));
output = JSONObject.valueToString(nonJsonString); output = JSONObject.valueToString(nonJsonString);
assertTrue("String values should be equal", "\"\"".equals(output)); assertTrue("String values should be equal", "\"\"".equals(output));
} finally {
writer.close();
}
} }
/** /**

View file

@ -3,6 +3,7 @@ package org.json.junit;
/** /**
* An enum that contains getters and some internal fields * An enum that contains getters and some internal fields
*/ */
@SuppressWarnings("boxing")
public enum MyEnumField { public enum MyEnumField {
VAL1(1, "val 1"), VAL1(1, "val 1"),
VAL2(2, "val 2"), VAL2(2, "val 2"),
@ -15,12 +16,13 @@ public enum MyEnumField {
this.intVal = intVal; this.intVal = intVal;
} }
public String getValue() { public String getValue() {
return value; return this.value;
} }
public Integer getIntVal() { public Integer getIntVal() {
return intVal; return this.intVal;
} }
@Override
public String toString(){ public String toString(){
return value; return this.value;
} }
} }

View file

@ -3,6 +3,7 @@ package org.json.junit;
/** /**
* Need a class with some public data members for testing * Need a class with some public data members for testing
*/ */
@SuppressWarnings("boxing")
public class MyPublicClass { public class MyPublicClass {
public Integer publicInt = 42; public Integer publicInt = 42;
public String publicString = "abc"; public String publicString = "abc";

View file

@ -6,6 +6,7 @@ import java.util.*;
* A resource bundle class * A resource bundle class
*/ */
public class StringsResourceBundle extends ListResourceBundle { public class StringsResourceBundle extends ListResourceBundle {
@Override
public Object[][] getContents() { public Object[][] getContents() {
return contents; return contents;
} }

View file

@ -4,11 +4,8 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONML;
import org.json.JSONObject; import org.json.JSONObject;
import org.json.XML; import org.json.XML;
import org.junit.Rule; import org.junit.Rule;