1
0
Fork 0
mirror of https://github.com/ethauvin/JSON-java.git synced 2025-06-18 00:10:51 -07:00
This commit is contained in:
stleary 2016-01-03 21:39:44 -06:00
parent ace08f1944
commit 706d898648
22 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,230 @@
package org.json.junit;
import static org.junit.Assert.*;
import org.junit.Test;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.CDL;
/**
* Tests for CDL.java.
* CDL provides an application level API, but it is not used by the
* reference app. To test it, strings will be converted to JSON-Java classes
* and then converted back.
*/
public class CDLTest {
/**
* String of lines where the column names are in the first row,
* and all subsequent rows are values. All keys and values should be legal.
*/
String lines = new String(
"Col 1, Col 2, \tCol 3, Col 4, Col 5, Col 6, Col 7\n" +
"val1, val2, val3, val4, val5, val6, val7\n" +
"1, 2, 3, 4\t, 5, 6, 7\n" +
"true, false, true, true, false, false, false\n" +
"0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" +
"\"va\tl1\", \"v\bal2\", \"val3\", \"val\f4\", \"val5\", va\'l6, val7\n"
);
/**
* CDL.toJSONArray() adds all values asstrings, with no filtering or
* conversions. For testing, this means that the expected JSONObject
* values all must be quoted in the cases where the JSONObject parsing
* might normally convert the value into a non-string.
*/
String expectedLines = new String(
"[{Col 1:val1, Col 2:val2, Col 3:val3, Col 4:val4, Col 5:val5, Col 6:val6, Col 7:val7}, "+
"{Col 1:\"1\", Col 2:\"2\", Col 3:\"3\", Col 4:\"4\", Col 5:\"5\", Col 6:\"6\", Col 7:\"7\"}, "+
"{Col 1:\"true\", Col 2:\"false\", Col 3:\"true\", Col 4:\"true\", Col 5:\"false\", Col 6:\"false\", Col 7:\"false\"}, "+
"{Col 1:\"0.23\", Col 2:\"57.42\", Col 3:\"5e27\", Col 4:\"-234.879\", Col 5:\"2.34e5\", Col 6:\"0.0\", Col 7:\"9e-3\"}, "+
"{Col 1:\"va\tl1\", Col 2:\"v\bal2\", Col 3:val3, Col 4:\"val\f4\", Col 5:val5, Col 6:va\'l6, Col 7:val7}]");
/**
* Attempts to create a JSONArray from a null string.
* Expect a NullPointerException.
*/
@Test(expected=NullPointerException.class)
public void exceptionOnNullString() {
String nullStr = null;
CDL.toJSONArray(nullStr);
}
/**
* Attempts to create a JSONArray from a string with unbalanced quotes
* in column title line. Expects a JSONException.
*/
@Test
public void unbalancedQuoteInName() {
String badLine = "Col1, \"Col2\nVal1, Val2";
try {
CDL.toJSONArray(badLine);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Missing close quote '\"'. at 12 [character 0 line 2]".
equals(e.getMessage()));
}
}
/**
* Attempts to create a JSONArray from a string with unbalanced quotes
* in value line. Expects a JSONException.
*/
@Test
public void unbalancedQuoteInValue() {
String badLine = "Col1, Col2\n\"Val1, Val2";
try {
CDL.toJSONArray(badLine);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Missing close quote '\"'. at 23 [character 12 line 3]".
equals(e.getMessage()));
}
}
/**
* Attempts to create a JSONArray from a string with null char
* in column title line. Expects a JSONException.
*/
@Test
public void nullInName() {
String badLine = "C\0ol1, Col2\nVal1, Val2";
try {
CDL.toJSONArray(badLine);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Bad character 'o' (111). at 3 [character 4 line 1]".
equals(e.getMessage()));
}
}
/**
* call toString with a null array
*/
@Test(expected=NullPointerException.class)
public void nullJSONArrayToString() {
CDL.toString((JSONArray)null);
}
/**
* Create a JSONArray from an empty string
*/
@Test
public void emptyString() {
String emptyStr = "";
JSONArray jsonArray = CDL.toJSONArray(emptyStr);
assertTrue("CDL should return null when the input string is empty",
jsonArray == null);
}
/**
* Create a JSONArray with only 1 row
*/
@Test
public void onlyColumnNames() {
String columnNameStr = "col1, col2, col3";
JSONArray jsonArray = CDL.toJSONArray(columnNameStr);
assertTrue("CDL should return null when only 1 row is given",
jsonArray == null);
}
/**
* Create a JSONArray from string containing only whitespace and commas
*/
@Test
public void emptyLinesToJSONArray() {
String str = " , , , \n , , , ";
JSONArray jsonArray = CDL.toJSONArray(str);
assertTrue("JSONArray should be null for no content",
jsonArray == null);
}
/**
* call toString with a null array
*/
@Test
public void emptyJSONArrayToString() {
JSONArray jsonArray = new JSONArray();
String str = CDL.toString(jsonArray);
assertTrue("CDL should return null for toString(null)",
str == null);
}
/**
* call toString with a null arrays for names and values
*/
@Test
public void nullJSONArraysToString() {
String str = CDL.toString(null, null);
assertTrue("CDL should return null for toString(null)",
str == null);
}
/**
* Given a JSONArray that was not built by CDL, some chars may be
* found that would otherwise be filtered out by CDL.
*/
@Test
public void checkSpecialChars() {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonArray.put(jsonObject);
// \r will be filtered from name
jsonObject.put("Col \r1", "V1");
// \r will be filtered from value
jsonObject.put("Col 2", "V2\r");
assertTrue("expected length should be 1",jsonArray.length() == 1);
String cdlStr = CDL.toString(jsonArray);
jsonObject = jsonArray.getJSONObject(0);
assertTrue(cdlStr.contains("\"Col 1\""));
assertTrue(cdlStr.contains("Col 2"));
assertTrue(cdlStr.contains("V1"));
assertTrue(cdlStr.contains("\"V2\""));
}
/**
* Create a JSONArray from a string of lines
*/
@Test
public void textToJSONArray() {
JSONArray jsonArray = CDL.toJSONArray(lines);
JSONArray expectedJsonArray = new JSONArray(expectedLines);
Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray);
}
/**
* Create a JSONArray from a JSONArray of titles and a
* string of value lines
*/
@Test
public void jsonArrayToJSONArray() {
String nameArrayStr = "[Col1, Col2]";
String values = "V1, V2";
JSONArray nameJSONArray = new JSONArray(nameArrayStr);
JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values);
JSONArray expectedJsonArray = new JSONArray("[{Col1:V1,Col2:V2}]");
Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray);
}
/**
* Create a JSONArray from a string of lines,
* then convert to string and then back to JSONArray
*/
@Test
public void textToJSONArrayAndBackToString() {
JSONArray jsonArray = CDL.toJSONArray(lines);
String jsonStr = CDL.toString(jsonArray);
JSONArray finalJsonArray = CDL.toJSONArray(jsonStr);
JSONArray expectedJsonArray = new JSONArray(expectedLines);
Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray);
}
}

View file

@ -0,0 +1,186 @@
package org.json.junit;
import static org.junit.Assert.*;
import java.util.*;
import org.json.*;
import org.junit.Test;
import com.jayway.jsonpath.*;
/**
* HTTP cookie specification RFC6265: http://tools.ietf.org/html/rfc6265
* <p>
* A cookie list is a JSONObject whose members are presumed to be cookie
* name/value pairs. Entries are unescaped while being added, and escaped in
* the toString() output.
* Unescaping means to convert %hh hex strings to the ascii equivalent
* and converting '+' to ' '.
* Escaping converts '+', '%', '=', ';' and ascii control chars to %hh hex strings.
* <p>
* CookieList should not be considered as just a list of Cookie objects:<br>
* - CookieList stores a cookie name/value pair as a single entry; Cookie stores
* it as 2 entries (key="name" and key="value").<br>
* - CookieList requires multiple name/value pairs as input; Cookie allows the
* 'secure' name with no associated value<br>
* - CookieList has no special handling for attribute name/value pairs.<br>
*/
public class CookieListTest {
/**
* Attempts to create a CookieList from a null string.
* Expects a NullPointerException.
*/
@Test(expected=NullPointerException.class)
public void nullCookieListException() {
String cookieStr = null;
CookieList.toJSONObject(cookieStr);
}
/**
* Attempts to create a CookieList from a malformed string.
* Expects a JSONException.
*/
@Test
public void malFormedCookieListException() {
String cookieStr = "thisCookieHasNoEqualsChar";
try {
CookieList.toJSONObject(cookieStr);
assertTrue("should throw an exception", false);
} catch (JSONException e) {
/**
* Not sure of the missing char, but full string compare fails
*/
assertTrue("Expecting an exception message",
e.getMessage().startsWith("Expected '=' and instead saw '") &&
e.getMessage().endsWith("' at 27 [character 28 line 1]"));
}
}
/**
* Creates a CookieList from an empty string.
*/
@Test
public void emptyStringCookieList() {
String cookieStr = "";
JSONObject jsonObject = CookieList.toJSONObject(cookieStr);
assertTrue(jsonObject.length() == 0);
}
/**
* CookieList with the simplest cookie - a name/value pair with no delimiter.
*/
@Test
public void simpleCookieList() {
String cookieStr = "SID=31d4d96e407aad42";
JSONObject jsonObject = CookieList.toJSONObject(cookieStr);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("Expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID")));
}
/**
* CookieList with a single a cookie which has a name/value pair and delimiter.
*/
@Test
public void simpleCookieListWithDelimiter() {
String cookieStr = "SID=31d4d96e407aad42;";
JSONObject jsonObject = CookieList.toJSONObject(cookieStr);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("Expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID")));
}
/**
* CookieList with multiple cookies consisting of name/value pairs
* with delimiters.
*/
@Test
public void multiPartCookieList() {
String cookieStr =
"name1=myCookieValue1; "+
" name2=myCookieValue2;"+
"name3=myCookieValue3;"+
" name4=myCookieValue4; "+
"name5=myCookieValue5;"+
" name6=myCookieValue6;";
JSONObject jsonObject = CookieList.toJSONObject(cookieStr);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("Expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1")));
assertTrue("expected myCookieValue2", "myCookieValue2".equals(JsonPath.read(doc, "$.name2")));
assertTrue("expected myCookieValue3", "myCookieValue3".equals(JsonPath.read(doc, "$.name3")));
assertTrue("expected myCookieValue4", "myCookieValue4".equals(JsonPath.read(doc, "$.name4")));
assertTrue("expected myCookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5")));
assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6")));
}
/**
* CookieList from a JSONObject with valid key and null value
*/
@Test
public void convertCookieListWithNullValueToString() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", JSONObject.NULL);
String cookieToStr = CookieList.toString(jsonObject);
assertTrue("toString() should be empty", "".equals(cookieToStr));
}
/**
* CookieList with multiple entries converted to a JSON document.
*/
@Test
public void convertCookieListToString() {
String cookieStr =
"name1=myCookieValue1; "+
" name2=myCookieValue2;"+
"name3=myCookieValue3;"+
" name4=myCookieValue4; "+
"name5=myCookieValue5;"+
" name6=myCookieValue6;";
JSONObject jsonObject = CookieList.toJSONObject(cookieStr);
// exercise CookieList.toString()
String cookieListString = CookieList.toString(jsonObject);
// have to convert it back for validation
jsonObject = CookieList.toJSONObject(cookieListString);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("Expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1")));
assertTrue("expected myCookieValue2", "myCookieValue2".equals(JsonPath.read(doc, "$.name2")));
assertTrue("expected myCookieValue3", "myCookieValue3".equals(JsonPath.read(doc, "$.name3")));
assertTrue("expected myCookieValue4", "myCookieValue4".equals(JsonPath.read(doc, "$.name4")));
assertTrue("expected myCookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5")));
assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6")));
}
/**
* CookieList with multiple entries and some '+' chars and URL-encoded
* values converted to a JSON document.
*/
@Test
public void convertEncodedCookieListToString() {
String cookieStr =
"name1=myCookieValue1; "+
" name2=my+Cookie+Value+2;"+
"name3=my%2BCookie%26Value%3B3%3D;"+
" name4=my%25CookieValue4; "+
"name5=myCookieValue5;"+
" name6=myCookieValue6;";
JSONObject jsonObject = CookieList.toJSONObject(cookieStr);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("Expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1")));
assertTrue("expected my Cookie Value 2", "my Cookie Value 2".equals(JsonPath.read(doc, "$.name2")));
assertTrue("expected my+Cookie&Value;3=", "my+Cookie&Value;3=".equals(JsonPath.read(doc, "$.name3")));
assertTrue("expected my%CookieValue4", "my%CookieValue4".equals(JsonPath.read(doc, "$.name4")));
assertTrue("expected my%CookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5")));
assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6")));
}
}

View file

@ -0,0 +1,226 @@
package org.json.junit;
import static org.junit.Assert.*;
import org.json.*;
import org.junit.Test;
/**
* HTTP cookie specification: RFC6265
* <p>
* At its most basic, a cookie is a name=value pair. The value may be subdivided
* into other cookies, but that is not tested here. The cookie may also include
* certain named attributes, delimited by semicolons.
* <p>
* The Cookie.toString() method emits certain attributes if present: expires,
* domain, path, secure. All but secure are name-value pairs. Other attributes
* are not included in the toString() output.
* <p>
* A JSON-Java encoded cookie escapes '+', '%', '=', ';' with %hh values.
*/
public class CookieTest {
/**
* Attempts to create a JSONObject from a null string.
* Expects a NullPointerException.
*/
@Test(expected=NullPointerException.class)
public void nullCookieException() {
String cookieStr = null;
Cookie.toJSONObject(cookieStr);
}
/**
* Attempts to create a JSONObject from a cookie string with
* no '=' char.
* Expects a JSONException.
*/
@Test
public void malFormedNameValueException() {
String cookieStr = "thisCookieHasNoEqualsChar";
try {
Cookie.toJSONObject(cookieStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
e.getMessage().startsWith("Expected '=' and instead saw '")
&& e.getMessage().endsWith("' at 27 [character 28 line 1]"));
}
}
/**
* Attempts to create a JSONObject from a cookie string
* with embedded ';' char.
* Expects a JSONException.
*/
@Test
public void malFormedAttributeException() {
String cookieStr = "this=Cookie;myAttribute";
try {
Cookie.toJSONObject(cookieStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Missing '=' in cookie parameter. at 25 [character 26 line 1]".
equals(e.getMessage()));
}
}
/**
* Attempts to create a JSONObject from an empty cookie string.<br>
* Note: Cookie throws an exception, but CookieList does not.<br>
* Expects a JSONException
*/
@Test
public void emptyStringCookieException() {
String cookieStr = "";
try {
Cookie.toJSONObject(cookieStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
e.getMessage().startsWith("Expected '=' and instead saw '") &&
e.getMessage().endsWith("' at 2 [character 3 line 1]"));
}
}
/**
* Cookie from a simple name/value pair with no delimiter
*/
@Test
public void simpleCookie() {
String cookieStr = "SID=31d4d96e407aad42";
String expectedCookieStr = "{\"name\":\"SID\",\"value\":\"31d4d96e407aad42\"}";
JSONObject jsonObject = Cookie.toJSONObject(cookieStr);
JSONObject expectedJsonObject = new JSONObject(expectedCookieStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Store a cookie with all of the supported attributes in a
* JSONObject. The secure attribute, which has no value, is treated
* as a boolean.
*/
@Test
public void multiPartCookie() {
String cookieStr =
"PH=deleted; "+
" expires=Wed, 19-Mar-2014 17:53:53 GMT;"+
"path=/; "+
" domain=.yahoo.com;"+
"secure";
String expectedCookieStr =
"{"+
"\"name\":\"PH\","+
"\"value\":\"deleted\","+
"\"path\":\"/\","+
"\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+
"\"domain\":\".yahoo.com\","+
"\"secure\":true"+
"}";
JSONObject jsonObject = Cookie.toJSONObject(cookieStr);
JSONObject expectedJsonObject = new JSONObject(expectedCookieStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Cookie.toString() will omit the non-standard "thiswont=beIncluded"
* attribute, but the attribute is still stored in the JSONObject.
* This test confirms both behaviors.
*/
@Test
public void convertCookieToString() {
String cookieStr =
"PH=deleted; "+
" expires=Wed, 19-Mar-2014 17:53:53 GMT;"+
"path=/; "+
" domain=.yahoo.com;"+
"thisWont=beIncluded;"+
"secure";
String expectedCookieStr =
"{\"path\":\"/\","+
"\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+
"\"domain\":\".yahoo.com\","+
"\"name\":\"PH\","+
"\"secure\":true,"+
"\"value\":\"deleted\"}";
// Add the nonstandard attribute to the expected cookie string
String expectedDirectCompareCookieStr =
expectedCookieStr.replaceAll("\\{", "\\{\"thisWont\":\"beIncluded\",");
// convert all strings into JSONObjects
JSONObject jsonObject = Cookie.toJSONObject(cookieStr);
JSONObject expectedJsonObject = new JSONObject(expectedCookieStr);
JSONObject expectedDirectCompareJsonObject =
new JSONObject(expectedDirectCompareCookieStr);
// emit the string
String cookieToStr = Cookie.toString(jsonObject);
// create a final JSONObject from the string
JSONObject finalJsonObject = Cookie.toJSONObject(cookieToStr);
// JSONObject should contain the nonstandard string
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedDirectCompareJsonObject);
// JSONObject -> string -> JSONObject should not contain the nonstandard string
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
/**
* A string may be URL-encoded when converting to JSONObject.
* If found, '+' is converted to ' ', and %hh hex strings are converted
* to their ascii char equivalents. This test confirms the decoding
* behavior.
*/
@Test
public void convertEncodedCookieToString() {
String cookieStr =
"PH=deleted; "+
" expires=Wed,+19-Mar-2014+17:53:53+GMT;"+
"path=/%2Bthis/is%26/a/spec%3Bsegment%3D; "+
" domain=.yahoo.com;"+
"secure";
String expectedCookieStr =
"{\"path\":\"/+this/is&/a/spec;segment=\","+
"\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+
"\"domain\":\".yahoo.com\","+
"\"name\":\"PH\","+
"\"secure\":true,"+
"\"value\":\"deleted\"}";
JSONObject jsonObject = Cookie.toJSONObject(cookieStr);
JSONObject expectedJsonObject = new JSONObject(expectedCookieStr);
String cookieToStr = Cookie.toString(jsonObject);
JSONObject finalJsonObject = Cookie.toJSONObject(cookieToStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
/**
* A public API method performs a URL encoding for selected chars
* in a string. Control chars, '+', '%', '=', ';' are all encoded
* as %hh hex strings. The string is also trimmed.
* This test confirms that behavior.
*/
@Test
public void escapeString() {
String str = " +%\r\n\t\b%=;;; ";
String expectedStr = "%2b%25%0d%0a%09%08%25%3d%3b%3b%3b";
String actualStr = Cookie.escape(str);
assertTrue("expect escape() to encode correctly. Actual: " +actualStr+
" expected: " +expectedStr, expectedStr.equals(actualStr));
}
/**
* A public API method performs URL decoding for strings.
* '+' is converted to space and %hh hex strings are converted to
* their ascii equivalent values. The string is not trimmed.
* This test confirms that behavior.
*/
@Test
public void unescapeString() {
String str = " +%2b%25%0d%0a%09%08%25%3d%3b%3b%3b+ ";
String expectedStr = " +%\r\n\t\b%=;;; ";
String actualStr = Cookie.unescape(str);
assertTrue("expect unescape() to decode correctly. Actual: " +actualStr+
" expected: " +expectedStr, expectedStr.equals(actualStr));
}
}

View file

@ -0,0 +1,377 @@
package org.json.junit;
import static org.junit.Assert.*;
import java.util.*;
import org.json.*;
import org.junit.*;
import com.jayway.jsonpath.*;
/**
* Enums are not explicitly supported in JSON-Java. But because enums act like
* classes, all required behavior is already be present in some form.
* These tests explore how enum serialization works with JSON-Java.
*/
public class EnumTest {
/**
* To serialize an enum by its getters, use the JSONObject Object constructor.
* The JSONObject ctor handles enum like any other bean. A JSONobject
* is created whose entries are the getter name/value pairs.
*/
@Test
public void jsonObjectFromEnum() {
// If there are no getters then the object is empty.
MyEnum myEnum = MyEnum.VAL2;
JSONObject jsonObject = new JSONObject(myEnum);
assertTrue("simple enum has no getters", jsonObject.length() == 0);
// enum with a getters should create a non-empty object
MyEnumField myEnumField = MyEnumField.VAL2;
jsonObject = new JSONObject(myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider()
.parse(jsonObject.toString());
assertTrue("expecting 2 items in top level object", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expecting val 2", "val 2".equals(JsonPath.read(doc, "$.value")));
assertTrue("expecting 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal")));
/**
* class which contains enum instances. Each enum should be stored
* in its own JSONObject
*/
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL3);
jsonObject = new JSONObject(myEnumClass);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expecting 2 items in top level object", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expecting 2 items in myEnumField object", ((Map<?,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
assertTrue("expecting 0 items in myEnum object", ((Map<?,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
assertTrue("expecting 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal")));
assertTrue("expecting val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value")));
}
/**
* To serialize an enum by its set of allowed values, use getNames()
* and the the JSONObject Object with names constructor.
*/
@Test
public void jsonObjectFromEnumWithNames() {
String [] names;
JSONObject jsonObject;
MyEnum myEnum = MyEnum.VAL1;
names = JSONObject.getNames(myEnum);
// The values will be MyEnum fields
jsonObject = new JSONObject(myEnum, names);
// validate JSON object
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2")));
assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3")));
MyEnumField myEnumField = MyEnumField.VAL3;
names = JSONObject.getNames(myEnumField);
// The values will be MyEnmField fields
jsonObject = new JSONObject(myEnumField, names);
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2")));
assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3")));
}
/**
* To serialize by assigned value, use the put() methods. The value
* will be stored as a enum type.
*/
@Test
public void enumPut() {
JSONObject jsonObject = new JSONObject();
MyEnum myEnum = MyEnum.VAL2;
jsonObject.put("myEnum", myEnum);
MyEnumField myEnumField = MyEnumField.VAL1;
jsonObject.putOnce("myEnumField", myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level objects", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnum")));
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.myEnumField")));
JSONArray jsonArray = new JSONArray();
jsonArray.put(myEnum);
jsonArray.put(1, myEnumField);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 2 top level objects", ((List<?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$[1]")));
/**
* Leaving these tests because they exercise get, opt, and remove
*/
assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonArray.get(0)));
assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.opt(1)));
assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.remove(1)));
}
/**
* The default action of valueToString() is to call object.toString().
* For enums, this means the assigned value will be returned as a string.
*/
@Test
public void enumValueToString() {
String expectedStr1 = "\"VAL1\"";
String expectedStr2 = "\"VAL1\"";
MyEnum myEnum = MyEnum.VAL1;
MyEnumField myEnumField = MyEnumField.VAL1;
MyEnumClass myEnumClass = new MyEnumClass();
String str1 = JSONObject.valueToString(myEnum);
assertTrue("actual myEnum: "+str1+" expected: "+expectedStr1,
str1.equals(expectedStr1));
String str2 = JSONObject.valueToString(myEnumField);
assertTrue("actual myEnumField: "+str2+" expected: "+expectedStr2,
str2.equals(expectedStr2));
/**
* However, an enum within another class will not be rendered
* unless that class overrides default toString()
*/
String expectedStr3 = "\"org.json.junit.MyEnumClass@";
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL1);
String str3 = JSONObject.valueToString(myEnumClass);
assertTrue("actual myEnumClass: "+str3+" expected: "+expectedStr3,
str3.startsWith(expectedStr3));
}
/**
* In whatever form the enum was added to the JSONObject or JSONArray,
* json[Object|Array].toString should serialize it in a reasonable way.
*/
@Test
public void enumToString() {
MyEnum myEnum = MyEnum.VAL2;
JSONObject jsonObject = new JSONObject(myEnum);
String expectedStr = "{}";
assertTrue("myEnum toString() should be empty", expectedStr.equals(jsonObject.toString()));
MyEnumField myEnumField = MyEnumField.VAL2;
jsonObject = new JSONObject(myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected val 2", "val 2".equals(JsonPath.read(doc, "$.value")));
assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal")));
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL3);
jsonObject = new JSONObject(myEnumClass);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 2 myEnumField items", ((Map<?,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
assertTrue("expected 0 myEnum items", ((Map<?,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal")));
assertTrue("expected val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value")));
String [] names = JSONObject.getNames(myEnum);
jsonObject = new JSONObject(myEnum, names);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2")));
assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3")));
names = JSONObject.getNames(myEnumField);
jsonObject = new JSONObject(myEnumField, names);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 3 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 3);
assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2")));
assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3")));
expectedStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL2\"}";
jsonObject = new JSONObject();
jsonObject.putOpt("myEnum", myEnum);
jsonObject.putOnce("myEnumField", myEnumField);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnum")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnumField")));
JSONArray jsonArray = new JSONArray();
jsonArray.put(myEnum);
jsonArray.put(1, myEnumField);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 2 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[1]")));
}
/**
* Wrap should handle enums exactly the same way as the JSONObject(Object)
* constructor.
*/
@Test
public void wrap() {
MyEnum myEnum = MyEnum.VAL2;
JSONObject jsonObject = (JSONObject)JSONObject.wrap(myEnum);
assertTrue("simple enum has no getters", jsonObject.length() == 0);
MyEnumField myEnumField = MyEnumField.VAL2;
jsonObject = (JSONObject)JSONObject.wrap(myEnumField);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected val 2", "val 2".equals(JsonPath.read(doc, "$.value")));
assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal")));
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
myEnumClass.setMyEnumField(MyEnumField.VAL3);
jsonObject = (JSONObject)JSONObject.wrap(myEnumClass);
// validate JSON content
doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
assertTrue("expected 2 myEnumField items", ((Map<?,?>)(JsonPath.read(doc, "$.myEnumField"))).size() == 2);
assertTrue("expected 0 myEnum items", ((Map<?,?>)(JsonPath.read(doc, "$.myEnum"))).size() == 0);
assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal")));
assertTrue("expected val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value")));
}
/**
* It was determined that some API methods should be added to
* support enums:<br>
* JSONObject.getEnum(class, key)<br>
* JSONObject.optEnum(class, key)<br>
* JSONObject.optEnum(class, key, default)<br>
* JSONArray.getEnum(class, index)<br>
* JSONArray.optEnum(class, index)<br>
* JSONArray.optEnum(class, index, default)<br>
* <p>
* Exercise these enum API methods on JSONObject and JSONArray
*/
@Test
public void enumAPI() {
MyEnumClass myEnumClass = new MyEnumClass();
myEnumClass.setMyEnum(MyEnum.VAL1);
MyEnumField myEnumField = MyEnumField.VAL2;
JSONObject jsonObject = new JSONObject();
jsonObject.put("strKey", "value");
jsonObject.put("enumKey", myEnumField);
jsonObject.put("enumClassKey", myEnumClass);
// get a plain old enum
MyEnumField actualEnum = jsonObject.getEnum(MyEnumField.class, "enumKey");
assertTrue("get myEnumField", actualEnum == MyEnumField.VAL2);
// try to get the wrong value
try {
actualEnum = jsonObject.getEnum(MyEnumField.class, "strKey");
assertTrue("should throw an exception for wrong key", false);
} catch (Exception ignored) {}
// get a class that contains an enum
MyEnumClass actualEnumClass = (MyEnumClass)jsonObject.get("enumClassKey");
assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1);
// opt a plain old enum
actualEnum = jsonObject.optEnum(MyEnumField.class, "enumKey");
assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2);
// opt the wrong value
actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey");
assertTrue("opt null", actualEnum == null);
// opt a class that contains an enum
actualEnumClass = (MyEnumClass)jsonObject.opt("enumClassKey");
assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1);
// opt with default a plain old enum
actualEnum = jsonObject.optEnum(MyEnumField.class, "enumKey", null);
assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2);
// opt with default the wrong value
actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey", null);
assertTrue("opt null", actualEnum == null);
// opt with default an index that does not exist
actualEnum = jsonObject.optEnum(MyEnumField.class, "noKey", null);
assertTrue("opt null", actualEnum == null);
/**
* Exercise the proposed enum API methods on JSONArray
*/
JSONArray jsonArray = new JSONArray();
jsonArray.put("value");
jsonArray.put(myEnumField);
jsonArray.put(myEnumClass);
// get a plain old enum
actualEnum = jsonArray.getEnum(MyEnumField.class, 1);
assertTrue("get myEnumField", actualEnum == MyEnumField.VAL2);
// try to get the wrong value
try {
actualEnum = jsonArray.getEnum(MyEnumField.class, 0);
assertTrue("should throw an exception for wrong index", false);
} catch (Exception ignored) {}
// get a class that contains an enum
actualEnumClass = (MyEnumClass)jsonArray.get(2);
assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1);
// opt a plain old enum
actualEnum = jsonArray.optEnum(MyEnumField.class, 1);
assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2);
// opt the wrong value
actualEnum = jsonArray.optEnum(MyEnumField.class, 0);
assertTrue("opt null", actualEnum == null);
// opt a class that contains an enum
actualEnumClass = (MyEnumClass)jsonArray.opt(2);
assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1);
// opt with default a plain old enum
actualEnum = jsonArray.optEnum(MyEnumField.class, 1, null);
assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2);
// opt with default the wrong value
actualEnum = jsonArray.optEnum(MyEnumField.class, 0, null);
assertTrue("opt null", actualEnum == null);
// opt with default an index that does not exist
actualEnum = jsonArray.optEnum(MyEnumField.class, 3, null);
assertTrue("opt null", actualEnum == null);
}
}

View file

@ -0,0 +1,196 @@
package org.json.junit;
import static org.junit.Assert.*;
import org.json.*;
import org.junit.Test;
/**
* Unit tests for JSON-Java HTTP.java. See RFC7230.
*/
public class HTTPTest {
/**
* Attempt to call HTTP.toJSONObject() with a null string
* Expects a NUllPointerException.
*/
@Test(expected=NullPointerException.class)
public void nullHTTPException() {
String httpStr = null;
HTTP.toJSONObject(httpStr);
}
/**
* Attempt to call HTTP.toJSONObject() with a string containing
* an empty object. Expects a JSONException.
*/
@Test
public void notEnoughHTTPException() {
String httpStr = "{}";
JSONObject jsonObject = new JSONObject(httpStr);
try {
HTTP.toString(jsonObject);
assertTrue("Expected to throw exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Not enough material for an HTTP header.".equals(e.getMessage()));
}
}
/**
* Calling HTTP.toJSONObject() with an empty string will result in a
* populated JSONObject with keys but no values for Request-URI, Method,
* and HTTP-Version.
*/
@Test
public void emptyStringHTTPRequest() {
String httpStr = "";
String expectedHTTPStr = "{\"Request-URI\":\"\",\"Method\":\"\",\"HTTP-Version\":\"\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a Request-URI, Method,
* and HTTP-Version.
*/
@Test
public void simpleHTTPRequest() {
String httpStr = "GET /hello.txt HTTP/1.1";
String expectedHTTPStr =
"{\"Request-URI\":\"/hello.txt\",\"Method\":\"GET\",\"HTTP-Version\":\"HTTP/1.1\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a response string containing a
* HTTP-Version, Status-Code, and Reason.
*/
@Test
public void simpleHTTPResponse() {
String httpStr = "HTTP/1.1 200 OK";
String expectedHTTPStr =
"{\"HTTP-Version\":\"HTTP/1.1\",\"Status-Code\":\"200\",\"Reason-Phrase\":\"OK\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a full request string including
* request headers.
*/
@Test
public void extendedHTTPRequest() {
String httpStr =
"POST /enlighten/calais.asmx HTTP/1.1\n"+
"Host: api.opencalais.com\n"+
"Content-Type: text/xml; charset=utf-8\n"+
"Content-Length: 100\n"+
"SOAPAction: \"http://clearforest.com/Enlighten\"";
String expectedHTTPStr =
"{"+
"\"Request-URI\":\"/enlighten/calais.asmx\","+
"\"Host\":\"api.opencalais.com\","+
"\"Method\":\"POST\","+
"\"HTTP-Version\":\"HTTP/1.1\","+
"\"Content-Length\":\"100\","+
"\"Content-Type\":\"text/xml; charset=utf-8\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
/**
* Not too easy for JSONObject to parse a string with embedded quotes.
* For the sake of the test, add it here.
*/
expectedJsonObject.put("SOAPAction","\"http://clearforest.com/Enlighten\"");
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a full response string including
* response headers.
*/
@Test
public void extendedHTTPResponse() {
String httpStr =
"HTTP/1.1 200 OK\n"+
"Content-Type: text/xml; charset=utf-8\n"+
"Content-Length: 100\n";
String expectedHTTPStr =
"{\"HTTP-Version\":\"HTTP/1.1\","+
"\"Status-Code\":\"200\","+
"\"Content-Length\":\"100\","+
"\"Reason-Phrase\":\"OK\","+
"\"Content-Type\":\"text/xml; charset=utf-8\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a full POST request string including
* response headers, then convert it back into an HTTP string.
*/
@Test
public void convertHTTPRequestToString() {
String httpStr =
"POST /enlighten/calais.asmx HTTP/1.1\n"+
"Host: api.opencalais.com\n"+
"Content-Type: text/xml; charset=utf-8\n"+
"Content-Length: 100";
String expectedHTTPStr =
"{"+
"\"Request-URI\":\"/enlighten/calais.asmx\","+
"\"Host\":\"api.opencalais.com\","+
"\"Method\":\"POST\","+
"\"HTTP-Version\":\"HTTP/1.1\","+
"\"Content-Length\":\"100\","+
"\"Content-Type\":\"text/xml; charset=utf-8\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
String httpToStr = HTTP.toString(jsonObject);
/**
* JSONObject objects to crlfs and any trailing chars.
* For the sake of the test, simplify the resulting string
*/
httpToStr = httpToStr.replaceAll("("+HTTP.CRLF+HTTP.CRLF+")", "");
httpToStr = httpToStr.replaceAll(HTTP.CRLF, "\n");
JSONObject finalJsonObject = HTTP.toJSONObject(httpToStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
/**
* Call HTTP.toJSONObject() with a full response string including
* response headers, then convert it back into an HTTP string.
*/
@Test
public void convertHTTPResponseToString() {
String httpStr =
"HTTP/1.1 200 OK\n"+
"Content-Type: text/xml; charset=utf-8\n"+
"Content-Length: 100\n";
String expectedHTTPStr =
"{\"HTTP-Version\":\"HTTP/1.1\","+
"\"Status-Code\":\"200\","+
"\"Content-Length\":\"100\","+
"\"Reason-Phrase\":\"OK\","+
"\"Content-Type\":\"text/xml; charset=utf-8\"}";
JSONObject jsonObject = HTTP.toJSONObject(httpStr);
JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr);
String httpToStr = HTTP.toString(jsonObject);
/**
* JSONObject objects to crlfs and any trailing chars.
* For the sake of the test, simplify the resulting string
*/
httpToStr = httpToStr.replaceAll("("+HTTP.CRLF+HTTP.CRLF+")", "");
httpToStr = httpToStr.replaceAll(HTTP.CRLF, "\n");
JSONObject finalJsonObject = HTTP.toJSONObject(httpToStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
}

View file

@ -0,0 +1,689 @@
package org.json.junit;
import static org.junit.Assert.assertTrue;
import java.util.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import com.jayway.jsonpath.*;
/**
* Tests for JSON-Java JSONArray.java
*/
public class JSONArrayTest {
String arrayStr =
"["+
"true,"+
"false,"+
"\"true\","+
"\"false\","+
"\"hello\","+
"23.45e-4,"+
"\"23.45\","+
"42,"+
"\"43\","+
"["+
"\"world\""+
"],"+
"{"+
"\"key1\":\"value1\","+
"\"key2\":\"value2\","+
"\"key3\":\"value3\","+
"\"key4\":\"value4\""+
"},"+
"0,"+
"\"-1\""+
"]";
/**
* Attempt to create a JSONArray with a null string.
* Expects a NullPointerException.
*/
@Test(expected=NullPointerException.class)
public void nullException() {
String str = null;
new JSONArray(str);
}
/**
* Attempt to create a JSONArray with an empty string.
* Expects a JSONException.
*/
@Test
public void emptStr() {
String str = "";
try {
new JSONArray(str);
assertTrue("Should throw an exception", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"A JSONArray text must start with '[' at 1 [character 2 line 1]".
equals(e.getMessage()));
}
}
/**
* Attempt to create a JSONArray with a string as object that is
* not a JSON array doc.
* Expects a JSONException.
*/
@Test
public void badObject() {
String str = "abc";
try {
new JSONArray((Object)str);
assertTrue("Should throw an exception", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray initial value should be a string or collection or array.".
equals(e.getMessage()));
}
}
/**
* Verifies that the constructor has backwards compatability with RAW types pre-java5.
*/
@Test
public void verifyConstructor() {
final JSONArray expected = new JSONArray("[10]");
@SuppressWarnings("rawtypes")
Collection myRawC = Collections.singleton(Integer.valueOf(10));
JSONArray jaRaw = new JSONArray(myRawC);
Collection<Integer> myCInt = Collections.singleton(Integer.valueOf(10));
JSONArray jaInt = new JSONArray(myCInt);
Collection<Object> myCObj = Collections.singleton((Object) Integer
.valueOf(10));
JSONArray jaObj = new JSONArray(myCObj);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaInt));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObj));
}
/**
* Verifies that the put Collection has backwards compatability with RAW types pre-java5.
*/
@Test
public void verifyPutCollection() {
final JSONArray expected = new JSONArray("[[10]]");
@SuppressWarnings("rawtypes")
Collection myRawC = Collections.singleton(Integer.valueOf(10));
JSONArray jaRaw = new JSONArray();
jaRaw.put(myRawC);
Collection<Object> myCObj = Collections.singleton((Object) Integer
.valueOf(10));
JSONArray jaObj = new JSONArray();
jaObj.put(myCObj);
Collection<Integer> myCInt = Collections.singleton(Integer.valueOf(10));
JSONArray jaInt = new JSONArray();
jaInt.put(myCInt);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObj));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaInt));
}
/**
* Verifies that the put Map has backwards compatability with RAW types pre-java5.
*/
@Test
public void verifyPutMap() {
final JSONArray expected = new JSONArray("[{\"myKey\":10}]");
@SuppressWarnings("rawtypes")
Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10));
JSONArray jaRaw = new JSONArray();
jaRaw.put(myRawC);
Map<String, Object> myCStrObj = Collections.singletonMap("myKey",
(Object) Integer.valueOf(10));
JSONArray jaStrObj = new JSONArray();
jaStrObj.put(myCStrObj);
Map<String, Integer> myCStrInt = Collections.singletonMap("myKey",
Integer.valueOf(10));
JSONArray jaStrInt = new JSONArray();
jaStrInt.put(myCStrInt);
Map<?, ?> myCObjObj = Collections.singletonMap((Object) "myKey",
(Object) Integer.valueOf(10));
JSONArray jaObjObj = new JSONArray();
jaObjObj.put(myCObjObj);
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaRaw));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrObj));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaStrInt));
assertTrue(
"The RAW Collection should give me the same as the Typed Collection",
expected.similar(jaObjObj));
}
/**
* Create a JSONArray doc with a variety of different elements.
* Confirm that the values can be accessed via the get[type]() API methods
*/
@Test
public void getArrayValues() {
JSONArray jsonArray = new JSONArray(arrayStr);
// booleans
assertTrue("Array true",
true == jsonArray.getBoolean(0));
assertTrue("Array false",
false == jsonArray.getBoolean(1));
assertTrue("Array string true",
true == jsonArray.getBoolean(2));
assertTrue("Array string false",
false == jsonArray.getBoolean(3));
// strings
assertTrue("Array value string",
"hello".equals(jsonArray.getString(4)));
// doubles
assertTrue("Array double",
new Double(23.45e-4).equals(jsonArray.getDouble(5)));
assertTrue("Array string double",
new Double(23.45).equals(jsonArray.getDouble(6)));
// ints
assertTrue("Array value int",
new Integer(42).equals(jsonArray.getInt(7)));
assertTrue("Array value string int",
new Integer(43).equals(jsonArray.getInt(8)));
// nested objects
JSONArray nestedJsonArray = jsonArray.getJSONArray(9);
assertTrue("Array value JSONArray", nestedJsonArray != null);
JSONObject nestedJsonObject = jsonArray.getJSONObject(10);
assertTrue("Array value JSONObject", nestedJsonObject != null);
// longs
assertTrue("Array value long",
new Long(0).equals(jsonArray.getLong(11)));
assertTrue("Array value string long",
new Long(-1).equals(jsonArray.getLong(12)));
assertTrue("Array value null", jsonArray.isNull(-1));
}
/**
* Create a JSONArray doc with a variety of different elements.
* Confirm that attempting to get the wrong types via the get[type]()
* API methods result in JSONExceptions
*/
@Test
public void failedGetArrayValues() {
JSONArray jsonArray = new JSONArray(arrayStr);
try {
jsonArray.getBoolean(4);
assertTrue("expected getBoolean to fail", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray[4] is not a boolean.".equals(e.getMessage()));
}
try {
jsonArray.get(-1);
assertTrue("expected get to fail", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray[-1] not found.".equals(e.getMessage()));
}
try {
jsonArray.getDouble(4);
assertTrue("expected getDouble to fail", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray[4] is not a number.".equals(e.getMessage()));
}
try {
jsonArray.getInt(4);
assertTrue("expected getInt to fail", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray[4] is not a number.".equals(e.getMessage()));
}
try {
jsonArray.getJSONArray(4);
assertTrue("expected getJSONArray to fail", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray[4] is not a JSONArray.".equals(e.getMessage()));
}
try {
jsonArray.getJSONObject(4);
assertTrue("expected getJSONObject to fail", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray[4] is not a JSONObject.".equals(e.getMessage()));
}
try {
jsonArray.getLong(4);
assertTrue("expected getLong to fail", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray[4] is not a number.".equals(e.getMessage()));
}
try {
jsonArray.getString(5);
assertTrue("expected getString to fail", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"JSONArray[5] not a string.".equals(e.getMessage()));
}
}
/**
* Exercise JSONArray.join() by converting a JSONArray into a
* comma-separated string. Since this is very nearly a JSON document,
* array braces are added to the beginning and end prior to validation.
*/
@Test
public void join() {
JSONArray jsonArray = new JSONArray(arrayStr);
String joinStr = jsonArray.join(",");
// validate JSON
/**
* Don't need to remake the JSONArray to perform the parsing
*/
Object doc = Configuration.defaultConfiguration().jsonProvider().parse("["+joinStr+"]");
assertTrue("expected 13 items in top level object", ((List<?>)(JsonPath.read(doc, "$"))).size() == 13);
assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]")));
assertTrue("expected \"true\"", "true".equals(JsonPath.read(doc, "$[2]")));
assertTrue("expected \"false\"", "false".equals(JsonPath.read(doc, "$[3]")));
assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[4]")));
assertTrue("expected 0.002345", Double.valueOf(0.002345).equals(JsonPath.read(doc, "$[5]")));
assertTrue("expected \"23.45\"", "23.45".equals(JsonPath.read(doc, "$[6]")));
assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$[7]")));
assertTrue("expected \"43\"", "43".equals(JsonPath.read(doc, "$[8]")));
assertTrue("expected 1 item in [9]", ((List<?>)(JsonPath.read(doc, "$[9]"))).size() == 1);
assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[9][0]")));
assertTrue("expected 4 items in [10]", ((Map<?,?>)(JsonPath.read(doc, "$[10]"))).size() == 4);
assertTrue("expected value1", "value1".equals(JsonPath.read(doc, "$[10].key1")));
assertTrue("expected value2", "value2".equals(JsonPath.read(doc, "$[10].key2")));
assertTrue("expected value3", "value3".equals(JsonPath.read(doc, "$[10].key3")));
assertTrue("expected value4", "value4".equals(JsonPath.read(doc, "$[10].key4")));
assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$[11]")));
assertTrue("expected \"-1\"", "-1".equals(JsonPath.read(doc, "$[12]")));
}
/**
* Confirm the JSONArray.length() method
*/
@Test
public void length() {
assertTrue("expected empty JSONArray length 0",
new JSONArray().length() == 0);
JSONArray jsonArray = new JSONArray(arrayStr);
assertTrue("expected JSONArray length 13", jsonArray.length() == 13);
JSONArray nestedJsonArray = jsonArray.getJSONArray(9);
assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1);
}
/**
* Create a JSONArray doc with a variety of different elements.
* Confirm that the values can be accessed via the opt[type](index)
* and opt[type](index, default) API methods.
*/
@Test
public void opt() {
JSONArray jsonArray = new JSONArray(arrayStr);
assertTrue("Array opt value true",
Boolean.TRUE == jsonArray.opt(0));
assertTrue("Array opt value out of range",
null == jsonArray.opt(-1));
assertTrue("Array opt boolean",
Boolean.TRUE == jsonArray.optBoolean(0));
assertTrue("Array opt boolean default",
Boolean.FALSE == jsonArray.optBoolean(-1, Boolean.FALSE));
assertTrue("Array opt boolean implicit default",
Boolean.FALSE == jsonArray.optBoolean(-1));
assertTrue("Array opt double",
new Double(23.45e-4).equals(jsonArray.optDouble(5)));
assertTrue("Array opt double default",
new Double(1).equals(jsonArray.optDouble(0, 1)));
assertTrue("Array opt double default implicit",
new Double(jsonArray.optDouble(99)).isNaN());
assertTrue("Array opt int",
new Integer(42).equals(jsonArray.optInt(7)));
assertTrue("Array opt int default",
new Integer(-1).equals(jsonArray.optInt(0, -1)));
assertTrue("Array opt int default implicit",
0 == jsonArray.optInt(0));
JSONArray nestedJsonArray = jsonArray.optJSONArray(9);
assertTrue("Array opt JSONArray", nestedJsonArray != null);
assertTrue("Array opt JSONArray default",
null == jsonArray.optJSONArray(99));
JSONObject nestedJsonObject = jsonArray.optJSONObject(10);
assertTrue("Array opt JSONObject", nestedJsonObject != null);
assertTrue("Array opt JSONObject default",
null == jsonArray.optJSONObject(99));
assertTrue("Array opt long",
0 == jsonArray.optLong(11));
assertTrue("Array opt long default",
-2 == jsonArray.optLong(-1, -2));
assertTrue("Array opt long default implicit",
0 == jsonArray.optLong(-1));
assertTrue("Array opt string",
"hello".equals(jsonArray.optString(4)));
assertTrue("Array opt string default implicit",
"".equals(jsonArray.optString(-1)));
}
/**
* Exercise the JSONArray.put(value) method with various parameters
* and confirm the resulting JSONArray.
*/
@Test
public void put() {
JSONArray jsonArray = new JSONArray();
// index 0
jsonArray.put(true);
// 1
jsonArray.put(false);
String jsonArrayStr =
"["+
"hello,"+
"world"+
"]";
// 2
jsonArray.put(new JSONArray(jsonArrayStr));
// 3
jsonArray.put(2.5);
// 4
jsonArray.put(1);
// 5
jsonArray.put(45L);
// 6
jsonArray.put("objectPut");
String jsonObjectStr =
"{"+
"\"key10\":\"val10\","+
"\"key20\":\"val20\","+
"\"key30\":\"val30\""+
"}";
JSONObject jsonObject = new JSONObject(jsonObjectStr);
// 7
jsonArray.put(jsonObject);
Map<String, Object> map = new HashMap<String, Object>();
map.put("k1", "v1");
// 8
jsonArray.put(map);
Collection<Object> collection = new ArrayList<Object>();
collection.add(1);
collection.add(2);
// 9
jsonArray.put(collection);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 10 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 10);
assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]")));
assertTrue("expected 2 items in [2]", ((List<?>)(JsonPath.read(doc, "$[2]"))).size() == 2);
assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[2][0]")));
assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[2][1]")));
assertTrue("expected 2.5", Double.valueOf(2.5).equals(JsonPath.read(doc, "$[3]")));
assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[4]")));
assertTrue("expected 45", Integer.valueOf(45).equals(JsonPath.read(doc, "$[5]")));
assertTrue("expected objectPut", "objectPut".equals(JsonPath.read(doc, "$[6]")));
assertTrue("expected 3 items in [7]", ((Map<?,?>)(JsonPath.read(doc, "$[7]"))).size() == 3);
assertTrue("expected val10", "val10".equals(JsonPath.read(doc, "$[7].key10")));
assertTrue("expected val20", "val20".equals(JsonPath.read(doc, "$[7].key20")));
assertTrue("expected val30", "val30".equals(JsonPath.read(doc, "$[7].key30")));
assertTrue("expected 1 item in [8]", ((Map<?,?>)(JsonPath.read(doc, "$[8]"))).size() == 1);
assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$[8].k1")));
assertTrue("expected 2 items in [9]", ((List<?>)(JsonPath.read(doc, "$[9]"))).size() == 2);
assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[9][0]")));
assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[9][1]")));
}
/**
* Exercise the JSONArray.put(index, value) method with various parameters
* and confirm the resulting JSONArray.
*/
@Test
public void putIndex() {
JSONArray jsonArray = new JSONArray();
// 1
jsonArray.put(1, false);
// index 0
jsonArray.put(0, true);
String jsonArrayStr =
"["+
"hello,"+
"world"+
"]";
// 2
jsonArray.put(2, new JSONArray(jsonArrayStr));
// 5
jsonArray.put(5, 45L);
// 4
jsonArray.put(4, 1);
// 3
jsonArray.put(3, 2.5);
// 6
jsonArray.put(6, "objectPut");
// 7 will be null
String jsonObjectStr =
"{"+
"\"key10\":\"val10\","+
"\"key20\":\"val20\","+
"\"key30\":\"val30\""+
"}";
JSONObject jsonObject = new JSONObject(jsonObjectStr);
jsonArray.put(8, jsonObject);
Collection<Object> collection = new ArrayList<Object>();
collection.add(1);
collection.add(2);
jsonArray.put(9,collection);
Map<String, Object> map = new HashMap<String, Object>();
map.put("k1", "v1");
jsonArray.put(10, map);
try {
jsonArray.put(-1, "abc");
assertTrue("put index < 0 should have thrown exception", false);
} catch(Exception ignored) {}
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 11 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 11);
assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]")));
assertTrue("expected 2 items in [2]", ((List<?>)(JsonPath.read(doc, "$[2]"))).size() == 2);
assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[2][0]")));
assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[2][1]")));
assertTrue("expected 2.5", Double.valueOf(2.5).equals(JsonPath.read(doc, "$[3]")));
assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[4]")));
assertTrue("expected 45", Integer.valueOf(45).equals(JsonPath.read(doc, "$[5]")));
assertTrue("expected objectPut", "objectPut".equals(JsonPath.read(doc, "$[6]")));
assertTrue("expected null", null == JsonPath.read(doc, "$[7]"));
assertTrue("expected 3 items in [8]", ((Map<?,?>)(JsonPath.read(doc, "$[8]"))).size() == 3);
assertTrue("expected val10", "val10".equals(JsonPath.read(doc, "$[8].key10")));
assertTrue("expected val20", "val20".equals(JsonPath.read(doc, "$[8].key20")));
assertTrue("expected val30", "val30".equals(JsonPath.read(doc, "$[8].key30")));
assertTrue("expected 2 items in [9]", ((List<?>)(JsonPath.read(doc, "$[9]"))).size() == 2);
assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[9][0]")));
assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[9][1]")));
assertTrue("expected 1 item in [10]", ((Map<?,?>)(JsonPath.read(doc, "$[10]"))).size() == 1);
assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$[10].k1")));
}
/**
* Exercise the JSONArray.remove(index) method
* and confirm the resulting JSONArray.
*/
@Test
public void remove() {
String arrayStr =
"["+
"1"+
"]";
JSONArray jsonArray = new JSONArray(arrayStr);
jsonArray.remove(0);
assertTrue("array should be empty", null == jsonArray.remove(5));
assertTrue("jsonArray should be empty", jsonArray.length() == 0);
}
/**
* Exercise the JSONArray.similar() method with various parameters
* and confirm the results when not similar.
*/
@Test
public void notSimilar() {
String arrayStr =
"["+
"1"+
"]";
JSONArray jsonArray = new JSONArray(arrayStr);
JSONArray otherJsonArray = new JSONArray();
assertTrue("arrays lengths differ", !jsonArray.similar(otherJsonArray));
JSONObject jsonObject = new JSONObject("{\"k1\":\"v1\"}");
JSONObject otherJsonObject = new JSONObject();
jsonArray = new JSONArray();
jsonArray.put(jsonObject);
otherJsonArray = new JSONArray();
otherJsonArray.put(otherJsonObject);
assertTrue("arrays JSONObjects differ", !jsonArray.similar(otherJsonArray));
JSONArray nestedJsonArray = new JSONArray("[1, 2]");
JSONArray otherNestedJsonArray = new JSONArray();
jsonArray = new JSONArray();
jsonArray.put(nestedJsonArray);
otherJsonArray = new JSONArray();
otherJsonArray.put(otherNestedJsonArray);
assertTrue("arrays nested JSONArrays differ",
!jsonArray.similar(otherJsonArray));
jsonArray = new JSONArray();
jsonArray.put("hello");
otherJsonArray = new JSONArray();
otherJsonArray.put("world");
assertTrue("arrays values differ",
!jsonArray.similar(otherJsonArray));
}
/**
* Convert an empty JSONArray to JSONObject
*/
@Test
public void toJSONObject() {
JSONArray names = new JSONArray();
JSONArray jsonArray = new JSONArray();
assertTrue("toJSONObject should return null",
null == jsonArray.toJSONObject(names));
}
/**
* Confirm the creation of a JSONArray from an array of ints
*/
@Test
public void objectArrayVsIsArray() {
int[] myInts = { 1, 2, 3, 4, 5, 6, 7 };
Object myObject = myInts;
JSONArray jsonArray = new JSONArray(myObject);
// validate JSON
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 7 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 7);
assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]")));
assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]")));
assertTrue("expected 4", Integer.valueOf(4).equals(JsonPath.read(doc, "$[3]")));
assertTrue("expected 5", Integer.valueOf(5).equals(JsonPath.read(doc, "$[4]")));
assertTrue("expected 6", Integer.valueOf(6).equals(JsonPath.read(doc, "$[5]")));
assertTrue("expected 7", Integer.valueOf(7).equals(JsonPath.read(doc, "$[6]")));
}
/**
* Exercise the JSONArray iterator.
*/
@Test
public void iterator() {
JSONArray jsonArray = new JSONArray(arrayStr);
Iterator<Object> it = jsonArray.iterator();
assertTrue("Array true",
Boolean.TRUE.equals(it.next()));
assertTrue("Array false",
Boolean.FALSE.equals(it.next()));
assertTrue("Array string true",
"true".equals(it.next()));
assertTrue("Array string false",
"false".equals(it.next()));
assertTrue("Array string",
"hello".equals(it.next()));
assertTrue("Array double",
new Double(23.45e-4).equals(it.next()));
assertTrue("Array string double",
new Double(23.45).equals(Double.parseDouble((String)it.next())));
assertTrue("Array value int",
new Integer(42).equals(it.next()));
assertTrue("Array value string int",
new Integer(43).equals(Integer.parseInt((String)it.next())));
JSONArray nestedJsonArray = (JSONArray)it.next();
assertTrue("Array value JSONArray", nestedJsonArray != null);
JSONObject nestedJsonObject = (JSONObject)it.next();
assertTrue("Array value JSONObject", nestedJsonObject != null);
assertTrue("Array value long",
new Long(0).equals(((Number) it.next()).longValue()));
assertTrue("Array value string long",
new Long(-1).equals(Long.parseLong((String) it.next())));
assertTrue("should be at end of array", !it.hasNext());
}
}

View file

@ -0,0 +1,701 @@
package org.json.junit;
import static org.junit.Assert.*;
import org.json.*;
import org.junit.Test;
/**
* Tests for org.json.JSONML.java
*
* Certain inputs are expected to result in exceptions. These tests are
* executed first. JSONML provides an API to:
* Convert an XML string into a JSONArray or a JSONObject.
* Convert a JSONArray or JSONObject into an XML string.
* Both fromstring and tostring operations operations should be symmetrical
* within the limits of JSONML.
* It should be possible to perform the following operations, which should
* result in the original string being recovered, within the limits of the
* underlying classes:
* Convert a string -> JSONArray -> string -> JSONObject -> string
* Convert a string -> JSONObject -> string -> JSONArray -> string
*
*/
public class JSONMLTest {
/**
* Attempts to transform a null XML string to JSON.
* Expects a NullPointerException
*/
@Test(expected=NullPointerException.class)
public void nullXMLException() {
String xmlStr = null;
JSONML.toJSONArray(xmlStr);
}
/**
* Attempts to transform an empty string to JSON.
* Expects a JSONException
*/
@Test
public void emptyXMLException() {
String xmlStr = "";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Bad XML at 1 [character 2 line 1]".
equals(e.getMessage()));
}
}
/**
* Attempts to call JSONML.toString() with a null JSONArray.
* Expects a NullPointerException.
*/
@Test(expected=NullPointerException.class)
public void nullJSONXMLException() {
/**
* Tries to convert a null JSONArray to XML.
*/
JSONArray jsonArray= null;
JSONML.toString(jsonArray);
}
/**
* Attempts to call JSONML.toString() with a null JSONArray.
* Expects a JSONException.
*/
@Test
public void emptyJSONXMLException() {
/**
* Tries to convert an empty JSONArray to XML.
*/
JSONArray jsonArray = new JSONArray();
try {
JSONML.toString(jsonArray);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONArray[0] not found.".
equals(e.getMessage()));
}
}
/**
* Attempts to transform an non-XML string to JSON.
* Expects a JSONException
*/
@Test
public void nonXMLException() {
/**
* Attempts to transform a nonXML string to JSON
*/
String xmlStr = "{ \"this is\": \"not xml\"}";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Bad XML at 25 [character 26 line 1]".
equals(e.getMessage()));
}
}
/**
* Attempts to transform a JSON document with XML content that
* does not follow JSONML conventions (element name is not first value
* in a nested JSONArray) to a JSONArray then back to string.
* Expects a JSONException
*/
@Test
public void emptyTagException() {
/**
* jsonArrayStr is used to build a JSONArray which is then
* turned into XML. For this transformation, all arrays represent
* elements and the first array entry is the name of the element.
* In this case, one of the arrays does not have a name
*/
String jsonArrayStr =
"[\"addresses\","+
"{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+
"\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+
// this array has no name
"["+
"[\"name\"],"+
"[\"nocontent\"],"+
"\">\""+
"]"+
"]";
JSONArray jsonArray = new JSONArray(jsonArrayStr);
try {
JSONML.toString(jsonArray);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"JSONArray[0] not a string.".
equals(e.getMessage()));
}
}
/**
* Attempts to transform a JSON document with XML content that
* does not follow JSONML conventions (element tag has an embedded space)
* to a JSONArray then back to string. Expects a JSONException
*/
@Test
public void spaceInTagException() {
/**
* jsonArrayStr is used to build a JSONArray which is then
* turned into XML. For this transformation, all arrays represent
* elements and the first array entry is the name of the element.
* In this case, one of the element names has an embedded space,
* which is not allowed.
*/
String jsonArrayStr =
"[\"addresses\","+
"{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+
"\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+
// this array has an invalid name
"[\"addr esses\","+
"[\"name\"],"+
"[\"nocontent\"],"+
"\">\""+
"]"+
"]";
JSONArray jsonArray = new JSONArray(jsonArrayStr);
try {
JSONML.toString(jsonArray);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"'addr esses' contains a space character.".
equals(e.getMessage()));
}
}
/**
* Attempts to transform a malformed XML document
* (element tag has a frontslash) to a JSONArray.\
* Expects a JSONException
*/
@Test
public void invalidSlashInTagException() {
/**
* xmlStr contains XML text which is transformed into a JSONArray.
* In this case, the XML is invalid because the 'name' element
* contains an invalid frontslash.
*/
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/x>\n"+
" <street>abc street</street>\n"+
" </address>\n"+
"</addresses>";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misshaped tag at 176 [character 14 line 7]".
equals(e.getMessage()));
}
}
/**
* Malformed XML text (invalid tagname) is transformed into a JSONArray.
* Expects a JSONException.
*/
@Test
public void invalidBangInTagException() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <!>\n"+
" </address>\n"+
"</addresses>";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misshaped meta tag at 216 [character 13 line 11]".
equals(e.getMessage()));
}
}
/**
* Malformed XML text (invalid tagname, no close bracket) is transformed\
* into a JSONArray. Expects a JSONException.
*/
@Test
public void invalidBangNoCloseInTagException() {
/**
* xmlStr contains XML text which is transformed into a JSONArray.
* In this case, the XML is invalid because an element
* starts with '!' and has no closing tag
*/
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <!\n"+
" </address>\n"+
"</addresses>";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misshaped meta tag at 215 [character 13 line 11]".
equals(e.getMessage()));
}
}
/**
* Malformed XML text (tagname with no close bracket) is transformed\
* into a JSONArray. Expects a JSONException.
*/
@Test
public void noCloseStartTagException() {
/**
* xmlStr contains XML text which is transformed into a JSONArray.
* In this case, the XML is invalid because an element
* has no closing '>'.
*/
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <abc\n"+
" </address>\n"+
"</addresses>";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misplaced '<' at 194 [character 5 line 10]".
equals(e.getMessage()));
}
}
/**
* Malformed XML text (endtag with no name) is transformed\
* into a JSONArray. Expects a JSONException.
*/
@Test
public void noCloseEndTagException() {
/**
* xmlStr contains XML text which is transformed into a JSONArray.
* In this case, the XML is invalid because an element
* has no name after the closing tag '</'.
*/
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <abc/>\n"+
" </>\n"+
"</addresses>";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Expected a closing name instead of '>'.".
equals(e.getMessage()));
}
}
/**
* Malformed XML text (endtag with no close bracket) is transformed\
* into a JSONArray. Expects a JSONException.
*/
@Test
public void noCloseEndBraceException() {
/**
* xmlStr contains XML text which is transformed into a JSONArray.
* In this case, the XML is invalid because an element
* has '>' after the closing tag '</' and name.
*/
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation=\"test.xsd\">\n"+
" <address>\n"+
" <name/>\n"+
" <abc/>\n"+
" </address\n"+
"</addresses>";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misplaced '<' at 206 [character 1 line 12]".
equals(e.getMessage()));
}
}
/**
* Malformed XML text (incomplete CDATA string) is transformed\
* into a JSONArray. Expects a JSONException.
*/
@Test
public void invalidCDATABangInTagException() {
/**
* xmlStr contains XML text which is transformed into a JSONArray.
* In this case, the XML is invalid because an element
* does not have a complete CDATA string.
*/
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name>Joe Tester</name>\n"+
" <![[]>\n"+
" </address>\n"+
"</addresses>";
try {
JSONML.toJSONArray(xmlStr);
assertTrue("Expecting an exception", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Expected 'CDATA[' at 204 [character 11 line 9]".
equals(e.getMessage()));
}
}
/**
* Convert an XML document into a JSONArray, then use JSONML.toString()
* to convert it into a string. This string is then converted back into
* a JSONArray. Both JSONArrays are compared against a control to
* confirm the contents.
*/
@Test
public void toJSONArray() {
/**
* xmlStr contains XML text which is transformed into a JSONArray.
* Each element becomes a JSONArray:
* 1st entry = elementname
* 2nd entry = attributes object (if present)
* 3rd entry = content (if present)
* 4th entry = child element JSONArrays (if present)
* The result is compared against an expected JSONArray.
* The transformed JSONArray is then transformed back into a string
* which is used to create a final JSONArray, which is also compared
* against the expected JSONArray.
*/
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
"xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
"<address attr1=\"attrValue1\" attr2=\"attrValue2\" attr3=\"attrValue3\">\n"+
"<name nameType=\"mine\">myName</name>\n"+
"<nocontent/>>\n"+
"</address>\n"+
"</addresses>";
String expectedStr =
"[\"addresses\","+
"{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+
"\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+
"[\"address\","+
"{\"attr1\":\"attrValue1\",\"attr2\":\"attrValue2\",\"attr3\":\"attrValue3\"},"+
"[\"name\", {\"nameType\":\"mine\"},\"myName\"],"+
"[\"nocontent\"],"+
"\">\""+
"]"+
"]";
JSONArray jsonArray = JSONML.toJSONArray(xmlStr);
JSONArray expectedJsonArray = new JSONArray(expectedStr);
String xmlToStr = JSONML.toString(jsonArray);
JSONArray finalJsonArray = JSONML.toJSONArray(xmlToStr);
Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray);
Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray);
}
/**
* Convert an XML document into a JSONObject. Use JSONML.toString() to
* convert it back into a string, and then re-convert it into a JSONObject.
* Both JSONObjects are compared against a control JSONObject to confirm
* the contents.
* <p>
* Next convert the XML document into a JSONArray. Use JSONML.toString() to
* convert it back into a string, and then re-convert it into a JSONArray.
* Both JSONArrays are compared against a control JSONArray to confirm
* the contents.
* <p>
* This test gives a comprehensive example of how the JSONML
* transformations work.
*/
@Test
public void toJSONObjectToJSONArray() {
/**
* xmlStr contains XML text which is transformed into a JSONObject,
* restored to XML, transformed into a JSONArray, and then restored
* to XML again. Both JSONObject and JSONArray should contain the same
* information and should produce the same XML, allowing for non-ordered
* attributes.
*
* Transformation to JSONObject:
* The elementName is stored as a string where key="tagName"
* Attributes are simply stored as key/value pairs
* If the element has either content or child elements, they are stored
* in a jsonArray with key="childNodes".
*
* Transformation to JSONArray:
* 1st entry = elementname
* 2nd entry = attributes object (if present)
* 3rd entry = content (if present)
* 4th entry = child element JSONArrays (if present)
*/
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
"xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
"<address addrType=\"my address\">\n"+
"<name nameType=\"my name\">Joe Tester</name>\n"+
"<street><![CDATA[Baker street 5]]></street>\n"+
"<NothingHere except=\"an attribute\"/>\n"+
"<TrueValue>true</TrueValue>\n"+
"<FalseValue>false</FalseValue>\n"+
"<NullValue>null</NullValue>\n"+
"<PositiveValue>42</PositiveValue>\n"+
"<NegativeValue>-23</NegativeValue>\n"+
"<DoubleValue>-23.45</DoubleValue>\n"+
"<Nan>-23x.45</Nan>\n"+
"<ArrayOfNum>\n"+
"<value>1</value>\n"+
"<value>2</value>\n"+
"<value><subValue svAttr=\"svValue\">abc</subValue></value>\n"+
"<value>3</value>\n"+
"<value>4.1</value>\n"+
"<value>5.2</value>\n"+
"</ArrayOfNum>\n"+
"</address>\n"+
"</addresses>";
String expectedJSONObjectStr =
"{"+
"\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+
"\"childNodes\":["+
"{"+
"\"childNodes\":["+
"{"+
"\"childNodes\":[\"Joe Tester\"],"+
"\"nameType\":\"my name\","+
"\"tagName\":\"name\""+
"},"+
"{"+
"\"childNodes\":[\"Baker street 5\"],"+
"\"tagName\":\"street\""+
"},"+
"{"+
"\"tagName\":\"NothingHere\","+
"\"except\":\"an attribute\""+
"},"+
"{"+
"\"childNodes\":[true],"+
"\"tagName\":\"TrueValue\""+
"},"+
"{"+
"\"childNodes\":[false],"+
"\"tagName\":\"FalseValue\""+
"},"+
"{"+
"\"childNodes\":[null],"+
"\"tagName\":\"NullValue\""+
"},"+
"{"+
"\"childNodes\":[42],"+
"\"tagName\":\"PositiveValue\""+
"},"+
"{"+
"\"childNodes\":[-23],"+
"\"tagName\":\"NegativeValue\""+
"},"+
"{"+
"\"childNodes\":[-23.45],"+
"\"tagName\":\"DoubleValue\""+
"},"+
"{"+
"\"childNodes\":[\"-23x.45\"],"+
"\"tagName\":\"Nan\""+
"},"+
"{"+
"\"childNodes\":["+
"{"+
"\"childNodes\":[1],"+
"\"tagName\":\"value\""+
"},"+
"{"+
"\"childNodes\":[2],"+
"\"tagName\":\"value\""+
"},"+
"{"+
"\"childNodes\":["+
"{"+
"\"childNodes\":[\"abc\"],"+
"\"svAttr\":\"svValue\","+
"\"tagName\":\"subValue\""+
"}"+
"],"+
"\"tagName\":\"value\""+
"},"+
"{"+
"\"childNodes\":[3],"+
"\"tagName\":\"value\""+
"},"+
"{"+
"\"childNodes\":[4.1],"+
"\"tagName\":\"value\""+
"},"+
"{"+
"\"childNodes\":[5.2],"+
"\"tagName\":\"value\""+
"}"+
"],"+
"\"tagName\":\"ArrayOfNum\""+
"}"+
"],"+
"\"addrType\":\"my address\","+
"\"tagName\":\"address\""+
"}"+
"],"+
"\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+
"\"tagName\":\"addresses\""+
"}";
String expectedJSONArrayStr =
"["+
"\"addresses\","+
"{"+
"\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+
"\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\""+
"},"+
"["+
"\"address\","+
"{"+
"\"addrType\":\"my address\""+
"},"+
"["+
"\"name\","+
"{"+
"\"nameType\":\"my name\""+
"},"+
"\"Joe Tester\""+
"],"+
"[\"street\",\"Baker street 5\"],"+
"["+
"\"NothingHere\","+
"{\"except\":\"an attribute\"}"+
"],"+
"[\"TrueValue\",true],"+
"[\"FalseValue\",false],"+
"[\"NullValue\",null],"+
"[\"PositiveValue\",42],"+
"[\"NegativeValue\",-23],"+
"[\"DoubleValue\",-23.45],"+
"[\"Nan\",\"-23x.45\"],"+
"["+
"\"ArrayOfNum\","+
"[\"value\",1],"+
"[\"value\",2],"+
"[\"value\","+
"["+
"\"subValue\","+
"{\"svAttr\":\"svValue\"},"+
"\"abc\""+
"],"+
"],"+
"[\"value\",3],"+
"[\"value\",4.1],"+
"[\"value\",5.2]"+
"]"+
"]"+
"]";
// make a JSONObject and make sure it looks as expected
JSONObject jsonObject = JSONML.toJSONObject(xmlStr);
JSONObject expectedJsonObject = new JSONObject(expectedJSONObjectStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
// restore the XML, then make another JSONObject and make sure it
// looks as expected
String jsonObjectXmlToStr = JSONML.toString(jsonObject);
JSONObject finalJsonObject = JSONML.toJSONObject(jsonObjectXmlToStr);
Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject);
// create a JSON array from the original string and make sure it
// looks as expected
JSONArray jsonArray = JSONML.toJSONArray(xmlStr);
JSONArray expectedJsonArray = new JSONArray(expectedJSONArrayStr);
Util.compareActualVsExpectedJsonArrays(jsonArray,expectedJsonArray);
// restore the XML, then make another JSONArray and make sure it
// looks as expected
String jsonArrayXmlToStr = JSONML.toString(jsonArray);
JSONArray finalJsonArray = JSONML.toJSONArray(jsonArrayXmlToStr);
Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray);
// lastly, confirm the restored JSONObject XML and JSONArray XML look
// reasonably similar
JSONObject jsonObjectFromObject = JSONML.toJSONObject(jsonObjectXmlToStr);
JSONObject jsonObjectFromArray = JSONML.toJSONObject(jsonArrayXmlToStr);
Util.compareActualVsExpectedJsonObjects(jsonObjectFromObject, jsonObjectFromArray);
}
/**
* Convert an XML document which contains embedded comments into
* a JSONArray. Use JSONML.toString() to turn it into a string, then
* reconvert it into a JSONArray. Compare both JSONArrays to a control
* JSONArray to confirm the contents.
* <p>
* This test shows how XML comments are handled.
*/
@Test
public void commentsInXML() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<!-- this is a comment -->\n"+
"<addresses>\n"+
"<address>\n"+
"<!-- <!--[CDATA[ this is -- <another> comment ]] -->\n"+
"<name>Joe Tester</name>\n"+
"<!-- this is a - multi line \n"+
"comment -->\n"+
"<street>Baker street 5</street>\n"+
"</address>\n"+
"</addresses>";
String expectedStr =
"[\"addresses\","+
"[\"address\","+
"[\"name\",\"Joe Tester\"],"+
"[\"street\",\"Baker street 5\"]"+
"]"+
"]";
JSONArray jsonArray = JSONML.toJSONArray(xmlStr);
JSONArray expectedJsonArray = new JSONArray(expectedStr);
String xmlToStr = JSONML.toString(jsonArray);
JSONArray finalJsonArray = JSONML.toJSONArray(xmlToStr);
Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray);
Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,307 @@
package org.json.junit;
import static org.junit.Assert.*;
import java.util.*;
import org.json.*;
import org.junit.Test;
import com.jayway.jsonpath.*;
/**
* Tests for JSON-Java JSONStringer and JSONWriter.
*/
public class JSONStringerTest {
/**
* Object with a null key.
* Expects a JSONException.
*/
@Test
public void nullKeyException() {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.object();
try {
jsonStringer.key(null);
assertTrue("Expected an exception", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"Null key.".
equals(e.getMessage()));
}
}
/**
* Add a key with no object.
* Expects a JSONException.
*/
@Test
public void outOfSequenceException() {
JSONStringer jsonStringer = new JSONStringer();
try {
jsonStringer.key("hi");
assertTrue("Expected an exception", false);
} catch (JSONException e) {
assertTrue("Expected an exception message",
"Misplaced key.".
equals(e.getMessage()));
}
}
/**
* Missplace an array.
* Expects a JSONException
*/
@Test
public void missplacedArrayException() {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.object().endObject();
try {
jsonStringer.array();
} catch (JSONException e) {
assertTrue("Expected an exception message",
"Misplaced array.".
equals(e.getMessage()));
}
}
/**
* Missplace an endErray.
* Expects a JSONException
*/
@Test
public void missplacedEndArrayException() {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.object();
try {
jsonStringer.endArray();
} catch (JSONException e) {
assertTrue("Expected an exception message",
"Misplaced endArray.".
equals(e.getMessage()));
}
}
/**
* Missplace an endObject.
* Expects a JSONException
*/
@Test
public void missplacedEndObjectException() {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.array();
try {
jsonStringer.endObject();
} catch (JSONException e) {
assertTrue("Expected an exception message",
"Misplaced endObject.".
equals(e.getMessage()));
}
}
/**
* Missplace an object.
* Expects a JSONException.
*/
@Test
public void missplacedObjectException() {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.object().endObject();
try {
jsonStringer.object();
} catch (JSONException e) {
assertTrue("Expected an exception message",
"Misplaced object.".
equals(e.getMessage()));
}
}
/**
* Exceeds implementation max nesting depth.
* Expects a JSONException
*/
@Test
public void exceedNestDepthException() {
try {
new JSONStringer().object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object().
key("k").object().key("k").object().key("k").object().key("k").object().key("k").object();
} catch (JSONException e) {
assertTrue("Expected an exception message",
"".
equals(e.getMessage()));
}
}
/**
* Build a JSON doc using JSONString API calls,
* then convert to JSONObject
*/
@Test
public void simpleObjectString() {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.object();
jsonStringer.key("trueValue").value(true);
jsonStringer.key("falseValue").value(false);
jsonStringer.key("nullValue").value(null);
jsonStringer.key("stringValue").value("hello world!");
jsonStringer.key("complexStringValue").value("h\be\tllo w\u1234orld!");
jsonStringer.key("intValue").value(42);
jsonStringer.key("doubleValue").value(-23.45e67);
jsonStringer.endObject();
String str = jsonStringer.toString();
JSONObject jsonObject = new JSONObject(str);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 7 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 7);
assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueValue")));
assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseValue")));
assertTrue("expected null", null == JsonPath.read(doc, "$.nullValue"));
assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.stringValue")));
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, "$.complexStringValue")));
assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.intValue")));
assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$.doubleValue")));
}
/**
* Build a JSON doc using JSONString API calls,
* then convert to JSONArray
*/
@Test
public void simpleArrayString() {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.array();
jsonStringer.value(true);
jsonStringer.value(false);
jsonStringer.value(null);
jsonStringer.value("hello world!");
jsonStringer.value(42);
jsonStringer.value(-23.45e67);
jsonStringer.endArray();
String str = jsonStringer.toString();
JSONArray jsonArray = new JSONArray(str);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
assertTrue("expected 6 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 6);
assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]")));
assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]")));
assertTrue("expected null", null == JsonPath.read(doc, "$[2]"));
assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$[3]")));
assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$[4]")));
assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$[5]")));
}
/**
* Build a nested JSON doc using JSONString API calls, then convert to
* JSONObject. Will create a long cascade of output by reusing the
* returned values..
*/
@Test
public void complexObjectString() {
JSONStringer jsonStringer = new JSONStringer();
jsonStringer.object().
key("trueValue").value(true).
key("falseValue").value(false).
key("nullValue").value(null).
key("stringValue").value("hello world!").
key("object2").object().
key("k1").value("v1").
key("k2").value("v2").
key("k3").value("v3").
key("array1").array().
value(1).
value(2).
object().
key("k4").value("v4").
key("k5").value("v5").
key("k6").value("v6").
key("array2").array().
value(5).
value(6).
value(7).
value(8).
endArray().
endObject().
value(3).
value(4).
endArray().
endObject().
key("complexStringValue").value("h\be\tllo w\u1234orld!").
key("intValue").value(42).
key("doubleValue").value(-23.45e67).
endObject();
String str = jsonStringer.toString();
JSONObject jsonObject = new JSONObject(str);
// validate JSON content
Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
assertTrue("expected 8 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 8);
assertTrue("expected 4 object2 items", ((Map<?,?>)(JsonPath.read(doc, "$.object2"))).size() == 4);
assertTrue("expected 5 array1 items", ((List<?>)(JsonPath.read(doc, "$.object2.array1"))).size() == 5);
assertTrue("expected 4 array[2] items", ((Map<?,?>)(JsonPath.read(doc, "$.object2.array1[2]"))).size() == 4);
assertTrue("expected 4 array1[2].array2 items", ((List<?>)(JsonPath.read(doc, "$.object2.array1[2].array2"))).size() == 4);
assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueValue")));
assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseValue")));
assertTrue("expected null", null == JsonPath.read(doc, "$.nullValue"));
assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.stringValue")));
assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.intValue")));
assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$.doubleValue")));
assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, "$.complexStringValue")));
assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$.object2.k1")));
assertTrue("expected v2", "v2".equals(JsonPath.read(doc, "$.object2.k2")));
assertTrue("expected v3", "v3".equals(JsonPath.read(doc, "$.object2.k3")));
assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.object2.array1[0]")));
assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.object2.array1[1]")));
assertTrue("expected v4", "v4".equals(JsonPath.read(doc, "$.object2.array1[2].k4")));
assertTrue("expected v5", "v5".equals(JsonPath.read(doc, "$.object2.array1[2].k5")));
assertTrue("expected v6", "v6".equals(JsonPath.read(doc, "$.object2.array1[2].k6")));
assertTrue("expected 5", Integer.valueOf(5).equals(JsonPath.read(doc, "$.object2.array1[2].array2[0]")));
assertTrue("expected 6", Integer.valueOf(6).equals(JsonPath.read(doc, "$.object2.array1[2].array2[1]")));
assertTrue("expected 7", Integer.valueOf(7).equals(JsonPath.read(doc, "$.object2.array1[2].array2[2]")));
assertTrue("expected 8", Integer.valueOf(8).equals(JsonPath.read(doc, "$.object2.array1[2].array2[3]")));
assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.object2.array1[3]")));
assertTrue("expected 4", Integer.valueOf(4).equals(JsonPath.read(doc, "$.object2.array1[4]")));
}
}

View file

@ -0,0 +1,20 @@
package org.json.junit;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
CDLTest.class,
CookieTest.class,
CookieListTest.class,
PropertyTest.class,
XMLTest.class,
JSONMLTest.class,
HTTPTest.class,
JSONStringerTest.class,
JSONObjectTest.class,
JSONArrayTest.class,
EnumTest.class
})
public class JunitTestSuite {
}

View file

@ -0,0 +1,16 @@
package org.json.junit;
import java.io.*;
/**
* Used in testing when Bean behavior is needed
*/
interface MyBean {
public Integer getIntKey();
public Double getDoubleKey();
public String getStringKey();
public String getEscapeStringKey();
public Boolean isTrueKey();
public Boolean isFalseKey();
public StringReader getStringReaderKey();
}

View file

@ -0,0 +1,11 @@
package org.json.junit;
import java.math.*;
/**
* Used in testing when a Bean containing big numbers is needed
*/
interface MyBigNumberBean {
public BigInteger getBigInteger();
public BigDecimal getBigDecimal();
}

View file

@ -0,0 +1,10 @@
package org.json.junit;
/**
* An enum with no methods or data
*/
public enum MyEnum {
VAL1,
VAL2,
VAL3;
}

View file

@ -0,0 +1,22 @@
package org.json.junit;
/**
* this is simply a class that contains some enum instances
*/
public class MyEnumClass {
private MyEnum myEnum;
private MyEnumField myEnumField;
public MyEnum getMyEnum() {
return myEnum;
}
public void setMyEnum(MyEnum myEnum) {
this.myEnum = myEnum;
}
public MyEnumField getMyEnumField() {
return myEnumField;
}
public void setMyEnumField(MyEnumField myEnumField) {
this.myEnumField = myEnumField;
}
}

View file

@ -0,0 +1,23 @@
package org.json.junit;
/**
* An enum that contains getters and some internal fields
*/
public enum MyEnumField {
VAL1(1, "val 1"),
VAL2(2, "val 2"),
VAL3(3, "val 3");
private String value;
private Integer intVal;
private MyEnumField(Integer intVal, String value) {
this.value = value;
this.intVal = intVal;
}
public String getValue() {
return value;
}
public Integer getIntVal() {
return intVal;
}
}

View file

@ -0,0 +1,14 @@
package org.json.junit;
import org.json.*;
/**
* Used in testing when a JSONString is needed
*/
class MyJsonString implements JSONString {
@Override
public String toJSONString() {
return "my string";
}
}

View file

@ -0,0 +1,9 @@
package org.json.junit;
/**
* Need a class with some public data members for testing
*/
public class MyPublicClass {
public Integer publicInt = 42;
public String publicString = "abc";
}

View file

@ -0,0 +1,98 @@
package org.json.junit;
import java.util.*;
import static org.junit.Assert.*;
import org.json.*;
import org.junit.Test;
/**
* Tests for JSON-Java Property
*/
public class PropertyTest {
/**
* JSONObject from null properties object should
* result in an empty JSONObject.
*/
@Test
public void shouldHandleNullProperties() {
Properties properties = null;
JSONObject jsonObject = Property.toJSONObject(properties);
assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
/**
* JSONObject from empty properties object should
* result in an empty JSONObject.
*/
@Test
public void shouldHandleEmptyProperties() {
Properties properties = new Properties();
JSONObject jsonObject = Property.toJSONObject(properties);
assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
/**
* JSONObject from simple properties object.
*/
@Test
public void shouldHandleProperties() {
Properties properties = new Properties();
properties.put("Illinois", "Springfield");
properties.put("Missouri", "Jefferson City");
properties.put("Washington", "Olympia");
properties.put("California", "Sacramento");
properties.put("Indiana", "Indianapolis");
JSONObject jsonObject = Property.toJSONObject(properties);
assertTrue("jsonObject should contain 5 items", jsonObject.length() == 5);
assertTrue("jsonObject should contain Illinois property",
"Springfield".equals(jsonObject.get("Illinois")));
assertTrue("jsonObject should contain Missouri property",
"Jefferson City".equals(jsonObject.get("Missouri")));
assertTrue("jsonObject should contain Washington property",
"Olympia".equals(jsonObject.get("Washington")));
assertTrue("jsonObject should contain California property",
"Sacramento".equals(jsonObject.get("California")));
assertTrue("jsonObject should contain Indiana property",
"Indianapolis".equals(jsonObject.get("Indiana")));
}
/**
* Null JSONObject toProperties() should result in an empty
* Properties object.
*/
@Test
public void shouldHandleNullJSONProperty() {
JSONObject jsonObject= null;
Properties properties = Property.toProperties(jsonObject);
assertTrue("properties should be empty",
properties.size() == 0);
}
/**
* Properties should convert to JSONObject, and back to
* Properties without changing.
*/
@Test
public void shouldHandleJSONProperty() {
Properties properties = new Properties();
properties.put("Illinois", "Springfield");
properties.put("Missouri", "Jefferson City");
properties.put("Washington", "Olympia");
properties.put("California", "Sacramento");
properties.put("Indiana", "Indianapolis");
JSONObject jsonObject = Property.toJSONObject(properties);
Properties jsonProperties = Property.toProperties(jsonObject);
assertTrue("property objects should match",
properties.equals(jsonProperties));
}
}

View file

@ -0,0 +1,18 @@
package org.json.junit;
import java.util.*;
/**
* A resource bundle class
*/
public class StringsResourceBundle extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"greetings.hello", "Hello, "},
{"greetings.world", "World!"},
{"farewells.later", "Later, "},
{"farewells.gator", "Alligator!"}
};
}

View file

@ -0,0 +1,19 @@
package org.json.junit;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
/**
* Invoke this class main method if you want to run unit tests from the
* command line. If successful, will print "true" to stdout.
*/
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}

View file

@ -0,0 +1,98 @@
package org.json.junit;
import static org.junit.Assert.*;
import java.util.*;
import org.json.*;
/**
* These are helpful utility methods that perform basic comparisons
* between various objects. In most cases, the comparisons are not
* order-dependent, or else the order is known.
*/
public class Util {
/**
* Compares two JSONArrays for equality.
* The arrays need not be in the same order.
* @param jsonArray created by the code to be tested
* @param expectedJsonArray created specifically for comparing
*/
public static void compareActualVsExpectedJsonArrays(JSONArray jsonArray,
JSONArray expectedJsonArray) {
assertTrue("jsonArray lengths should be equal",
jsonArray.length() == expectedJsonArray.length());
for (int i = 0; i < jsonArray.length(); ++i) {
Object value = jsonArray.get(i);
Object expectedValue = expectedJsonArray.get(i);
compareActualVsExpectedObjects(value, expectedValue);
}
}
/**
* Compares two JSONObjects for equality. The objects need not be
* in the same order
* @param jsonObject created by the code to be tested
* @param expectedJsonObject created specifically for comparing
*/
public static void compareActualVsExpectedJsonObjects(
JSONObject jsonObject, JSONObject expectedJsonObject) {
assertTrue("jsonObjects should have the same length",
jsonObject.length() == expectedJsonObject.length());
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Object value = jsonObject.get(key);
Object expectedValue = expectedJsonObject.get(key);
compareActualVsExpectedObjects(value, expectedValue);
}
}
/**
* Compare two objects for equality. Might be JSONArray, JSONObject,
* 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) {
if (value instanceof JSONObject && expectedValue instanceof JSONObject) {
// Compare JSONObjects
JSONObject jsonObject = (JSONObject)value;
JSONObject expectedJsonObject = (JSONObject)expectedValue;
compareActualVsExpectedJsonObjects(
jsonObject, expectedJsonObject);
} else if (value instanceof JSONArray && expectedValue instanceof JSONArray) {
// Compare JSONArrays
JSONArray jsonArray = (JSONArray)value;
JSONArray expectedJsonArray = (JSONArray)expectedValue;
compareActualVsExpectedJsonArrays(
jsonArray, expectedJsonArray);
} else {
/**
* Compare all other types using toString(). First, the types must
* also be equal, unless both are Number type. Certain helper
* classes (e.g. XML) may create Long instead of Integer for small
* int values.
*/
if (!(value instanceof Number && expectedValue instanceof Number)) {
// Non-Number and non-matching types
assertTrue("object types should be equal for actual: "+
value.toString()+" ("+
value.getClass().toString()+") expected: "+
expectedValue.toString()+" ("+
expectedValue.getClass().toString()+")",
value.getClass().toString().equals(
expectedValue.getClass().toString()));
}
/**
* Same types or both Numbers, compare by toString()
*/
assertTrue("string values should be equal for actual: "+
value.toString()+" expected: "+expectedValue.toString(),
value.toString().equals(expectedValue.toString()));
}
}
}

View file

@ -0,0 +1,726 @@
package org.json.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
/**
* Tests for JSON-Java XML.java
* Note: noSpace() will be tested by JSONMLTest
*/
public class XMLTest {
/**
* JUnit supports temporary files and folders that are cleaned up after the test.
* https://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/
*/
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
/**
* JSONObject from a null XML string.
* Expects a NullPointerException
*/
@Test(expected=NullPointerException.class)
public void shouldHandleNullXML() {
String xmlStr = null;
JSONObject jsonObject = XML.toJSONObject(xmlStr);
assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
/**
* Empty JSONObject from an empty XML string.
*/
@Test
public void shouldHandleEmptyXML() {
String xmlStr = "";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
/**
* Empty JSONObject from a non-XML string.
*/
@Test
public void shouldHandleNonXML() {
String xmlStr = "{ \"this is\": \"not xml\"}";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
assertTrue("xml string should be empty", jsonObject.length() == 0);
}
/**
* Invalid XML string (tag contains a frontslash).
* Expects a JSONException
*/
@Test
public void shouldHandleInvalidSlashInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/x>\n"+
" <street>abc street</street>\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
assertTrue("Expecting a JSONException", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misshaped tag at 176 [character 14 line 5]".
equals(e.getMessage()));
}
}
/**
* Invalid XML string ('!' char in tag)
* Expects a JSONException
*/
@Test
public void shouldHandleInvalidBangInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <!>\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
assertTrue("Expecting a JSONException", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misshaped meta tag at 215 [character 13 line 8]".
equals(e.getMessage()));
}
}
/**
* Invalid XML string ('!' char and no closing tag brace)
* Expects a JSONException
*/
@Test
public void shouldHandleInvalidBangNoCloseInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <!\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
assertTrue("Expecting a JSONException", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misshaped meta tag at 214 [character 13 line 8]".
equals(e.getMessage()));
}
}
/**
* Invalid XML string (no end brace for tag)
* Expects JSONException
*/
@Test
public void shouldHandleNoCloseStartTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <abc\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
assertTrue("Expecting a JSONException", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Misplaced '<' at 193 [character 4 line 7]".
equals(e.getMessage()));
}
}
/**
* Invalid XML string (partial CDATA chars in tag name)
* Expects JSONException
*/
@Test
public void shouldHandleInvalidCDATABangInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name>Joe Tester</name>\n"+
" <![[]>\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
assertTrue("Expecting a JSONException", false);
} catch (JSONException e) {
assertTrue("Expecting an exception message",
"Expected 'CDATA[' at 204 [character 11 line 6]".
equals(e.getMessage()));
}
}
/**
* Null JSONObject in XML.toString()
*/
@Test
public void shouldHandleNullJSONXML() {
JSONObject jsonObject= null;
String actualXml=XML.toString(jsonObject);
assertEquals("generated XML does not equal expected XML","\"null\"",actualXml);
}
/**
* Empty JSONObject in XML.toString()
*/
@Test
public void shouldHandleEmptyJSONXML() {
JSONObject jsonObject= new JSONObject();
String xmlStr = XML.toString(jsonObject);
assertTrue("xml string should be empty", xmlStr.length() == 0);
}
/**
* No SML start tag. The ending tag ends up being treated as content.
*/
@Test
public void shouldHandleNoStartTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <nocontent/>>\n"+
" </address>\n"+
"</addresses>";
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
"content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
JSONObject expectedJsonObject = new JSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Valid XML to JSONObject
*/
@Test
public void shouldHandleSimpleXML() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name>Joe Tester</name>\n"+
" <street>[CDATA[Baker street 5]</street>\n"+
" <NothingHere/>\n"+
" <TrueValue>true</TrueValue>\n"+
" <FalseValue>false</FalseValue>\n"+
" <NullValue>null</NullValue>\n"+
" <PositiveValue>42</PositiveValue>\n"+
" <NegativeValue>-23</NegativeValue>\n"+
" <DoubleValue>-23.45</DoubleValue>\n"+
" <Nan>-23x.45</Nan>\n"+
" <ArrayOfNum>1, 2, 3, 4.1, 5.2</ArrayOfNum>\n"+
" </address>\n"+
"</addresses>";
String expectedStr =
"{\"addresses\":{\"address\":{\"street\":\"[CDATA[Baker street 5]\","+
"\"name\":\"Joe Tester\",\"NothingHere\":\"\",TrueValue:true,\n"+
"\"FalseValue\":false,\"NullValue\":null,\"PositiveValue\":42,\n"+
"\"NegativeValue\":-23,\"DoubleValue\":-23.45,\"Nan\":-23x.45,\n"+
"\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+
"},\"xsi:noNamespaceSchemaLocation\":"+
"\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+
"XMLSchema-instance\"}}";
compareStringToJSONObject(xmlStr, expectedStr);
compareReaderToJSONObject(xmlStr, expectedStr);
compareFileToJSONObject(xmlStr, expectedStr);
}
/**
* Valid XML with comments to JSONObject
*/
@Test
public void shouldHandleCommentsInXML() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<!-- this is a comment -->\n"+
"<addresses>\n"+
" <address>\n"+
" <![CDATA[ this is -- <another> comment ]]>\n"+
" <name>Joe Tester</name>\n"+
" <!-- this is a - multi line \n"+
" comment -->\n"+
" <street>Baker street 5</street>\n"+
" </address>\n"+
"</addresses>";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+
"street 5\",\"name\":\"Joe Tester\",\"content\":\" this is -- "+
"<another> comment \"}}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Valid XML to XML.toString()
*/
@Test
public void shouldHandleToString() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name>[CDATA[Joe &amp; T &gt; e &lt; s &quot; t &apos; er]]</name>\n"+
" <street>Baker street 5</street>\n"+
" <ArrayOfNum>1, 2, 3, 4.1, 5.2</ArrayOfNum>\n"+
" </address>\n"+
"</addresses>";
String expectedStr =
"{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+
"\"name\":\"[CDATA[Joe & T > e < s \\\" t \\\' er]]\","+
"\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+
"},\"xsi:noNamespaceSchemaLocation\":"+
"\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+
"XMLSchema-instance\"}}";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
String xmlToStr = XML.toString(jsonObject);
JSONObject finalJsonObject = XML.toJSONObject(xmlToStr);
JSONObject expectedJsonObject = new JSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
/**
* Converting a JSON doc containing '>' content to JSONObject, then
* XML.toString() should result in valid XML.
*/
@Test
public void shouldHandleContentNoArraytoString() {
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
"content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
String finalStr = XML.toString(expectedJsonObject);
String expectedFinalStr = "<addresses><address><name/><nocontent/>&gt;"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
finalStr+"]", expectedFinalStr.equals(finalStr));
}
/**
* Converting a JSON doc containing a 'content' array to JSONObject, then
* XML.toString() should result in valid XML.
* TODO: This is probably an error in how the 'content' keyword is used.
*/
@Test
public void shouldHandleContentArraytoString() {
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
"content\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
String finalStr = XML.toString(expectedJsonObject);
String expectedFinalStr = "<addresses><address><name/><nocontent/>"+
"1\n2\n3"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
finalStr+"]", expectedFinalStr.equals(finalStr));
}
/**
* Converting a JSON doc containing a named array to JSONObject, then
* XML.toString() should result in valid XML.
*/
@Test
public void shouldHandleArraytoString() {
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+
"\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
String finalStr = XML.toString(expectedJsonObject);
String expectedFinalStr = "<addresses><address><name/><nocontent/>"+
"<something>1</something><something>2</something><something>3</something>"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
finalStr+"]", expectedFinalStr.equals(finalStr));
}
/**
* Tests that the XML output for empty arrays is consistent.
*/
@Test
public void shouldHandleEmptyArray(){
final JSONObject jo1 = new JSONObject();
jo1.put("array",new Object[]{});
final JSONObject jo2 = new JSONObject();
jo2.put("array",new JSONArray());
final String expected = "<jo></jo>";
String output1 = XML.toString(jo1,"jo");
assertTrue("Expected an empty root tag", expected.equals(output1));
String output2 = XML.toString(jo2,"jo");
assertTrue("Expected an empty root tag", expected.equals(output2));
}
/**
* Tests that the XML output for arrays is consistent when an internal array is empty.
*/
@Test
public void shouldHandleEmptyMultiArray(){
final JSONObject jo1 = new JSONObject();
jo1.put("arr",new Object[]{"One", new String[]{}, "Four"});
final JSONObject jo2 = new JSONObject();
jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{}), "Four"}));
final String expected = "<jo><arr>One</arr><arr></arr><arr>Four</arr></jo>";
String output1 = XML.toString(jo1,"jo");
assertTrue("Expected a matching array", expected.equals(output1));
String output2 = XML.toString(jo2,"jo");
assertTrue("Expected a matching array", expected.equals(output2));
}
/**
* Tests that the XML output for arrays is consistent when arrays are not empty.
*/
@Test
public void shouldHandleNonEmptyArray(){
final JSONObject jo1 = new JSONObject();
jo1.put("arr",new String[]{"One", "Two", "Three"});
final JSONObject jo2 = new JSONObject();
jo2.put("arr",new JSONArray(new String[]{"One", "Two", "Three"}));
final String expected = "<jo><arr>One</arr><arr>Two</arr><arr>Three</arr></jo>";
String output1 = XML.toString(jo1,"jo");
assertTrue("Expected a non empty root tag", expected.equals(output1));
String output2 = XML.toString(jo2,"jo");
assertTrue("Expected a non empty root tag", expected.equals(output2));
}
/**
* Tests that the XML output for arrays is consistent when arrays are not empty and contain internal arrays.
*/
@Test
public void shouldHandleMultiArray(){
final JSONObject jo1 = new JSONObject();
jo1.put("arr",new Object[]{"One", new String[]{"Two", "Three"}, "Four"});
final JSONObject jo2 = new JSONObject();
jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{"Two", "Three"}), "Four"}));
final String expected = "<jo><arr>One</arr><arr><array>Two</array><array>Three</array></arr><arr>Four</arr></jo>";
String output1 = XML.toString(jo1,"jo");
assertTrue("Expected a matching array", expected.equals(output1));
String output2 = XML.toString(jo2,"jo");
assertTrue("Expected a matching array", expected.equals(output2));
}
/**
* Converting a JSON doc containing a named array of nested arrays to
* JSONObject, then XML.toString() should result in valid XML.
*/
@Test
public void shouldHandleNestedArraytoString() {
String xmlStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+
"\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject jsonObject = new JSONObject(xmlStr);
String finalStr = XML.toString(jsonObject);
JSONObject finalJsonObject = XML.toJSONObject(finalStr);
String expectedStr = "<addresses><address><name/><nocontent/>"+
"<outer><array>1</array></outer><outer><array>2</array>"+
"</outer><outer><array>3</array></outer>"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
JSONObject expectedJsonObject = XML.toJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
/**
* Possible bug:
* Illegal node-names must be converted to legal XML-node-names.
* The given example shows 2 nodes which are valid for JSON, but not for XML.
* Therefore illegal arguments should be converted to e.g. an underscore (_).
*/
@Test
public void shouldHandleIllegalJSONNodeNames()
{
JSONObject inputJSON = new JSONObject();
inputJSON.append("123IllegalNode", "someValue1");
inputJSON.append("Illegal@node", "someValue2");
String result = XML.toString(inputJSON);
/*
* This is invalid XML. Names should not begin with digits or contain
* certain values, including '@'. One possible solution is to replace
* illegal chars with '_', in which case the expected output would be:
* <___IllegalNode>someValue1</___IllegalNode><Illegal_node>someValue2</Illegal_node>
*/
String expected = "<123IllegalNode>someValue1</123IllegalNode><Illegal@node>someValue2</Illegal@node>";
assertEquals(expected, result);
}
/**
* JSONObject with NULL value, to XML.toString()
*/
@Test
public void shouldHandleNullNodeValue()
{
JSONObject inputJSON = new JSONObject();
inputJSON.put("nullValue", JSONObject.NULL);
// This is a possible preferred result
// String expectedXML = "<nullValue/>";
/**
* This is the current behavior. JSONObject.NULL is emitted as
* the string, "null".
*/
String actualXML = "<nullValue>null</nullValue>";
String resultXML = XML.toString(inputJSON);
assertEquals(actualXML, resultXML);
}
/**
* Investigate exactly how the "content" keyword works
*/
@Test
public void contentOperations() {
/*
* When a standalone <!CDATA[...]] structure is found while parsing XML into a
* JSONObject, the contents are placed in a string value with key="content".
*/
String xmlStr = "<tag1></tag1><![CDATA[if (a < b && a > 0) then return]]><tag2></tag2>";
JSONObject jsonObject = XML.toJSONObject(xmlStr);
assertTrue("1. 3 items", 3 == jsonObject.length());
assertTrue("1. empty tag1", "".equals(jsonObject.get("tag1")));
assertTrue("1. empty tag2", "".equals(jsonObject.get("tag2")));
assertTrue("1. content found", "if (a < b && a > 0) then return".equals(jsonObject.get("content")));
// multiple consecutive standalone cdatas are accumulated into an array
xmlStr = "<tag1></tag1><![CDATA[if (a < b && a > 0) then return]]><tag2></tag2><![CDATA[here is another cdata]]>";
jsonObject = XML.toJSONObject(xmlStr);
assertTrue("2. 3 items", 3 == jsonObject.length());
assertTrue("2. empty tag1", "".equals(jsonObject.get("tag1")));
assertTrue("2. empty tag2", "".equals(jsonObject.get("tag2")));
assertTrue("2. content array found", jsonObject.get("content") instanceof JSONArray);
JSONArray jsonArray = jsonObject.getJSONArray("content");
assertTrue("2. array size", jsonArray.length() == 2);
assertTrue("2. content array entry 0", "if (a < b && a > 0) then return".equals(jsonArray.get(0)));
assertTrue("2. content array entry 1", "here is another cdata".equals(jsonArray.get(1)));
/*
* text content is accumulated in a "content" inside a local JSONObject.
* If there is only one instance, it is saved in the context (a different JSONObject
* from the calling code. and the content element is discarded.
*/
xmlStr = "<tag1>value 1</tag1>";
jsonObject = XML.toJSONObject(xmlStr);
assertTrue("3. 2 items", 1 == jsonObject.length());
assertTrue("3. value tag1", "value 1".equals(jsonObject.get("tag1")));
/*
* array-style text content (multiple tags with the same name) is
* accumulated in a local JSONObject with key="content" and value=JSONArray,
* saved in the context, and then the local JSONObject is discarded.
*/
xmlStr = "<tag1>value 1</tag1><tag1>2</tag1><tag1>true</tag1>";
jsonObject = XML.toJSONObject(xmlStr);
assertTrue("4. 1 item", 1 == jsonObject.length());
assertTrue("4. content array found", jsonObject.get("tag1") instanceof JSONArray);
jsonArray = jsonObject.getJSONArray("tag1");
assertTrue("4. array size", jsonArray.length() == 3);
assertTrue("4. content array entry 0", "value 1".equals(jsonArray.get(0)));
assertTrue("4. content array entry 1", jsonArray.getInt(1) == 2);
assertTrue("4. content array entry 2", jsonArray.getBoolean(2) == true);
/*
* Complex content is accumulated in a "content" field. For example, an element
* may contain a mix of child elements and text. Each text segment is
* accumulated to content.
*/
xmlStr = "<tag1>val1<tag2/>val2</tag1>";
jsonObject = XML.toJSONObject(xmlStr);
assertTrue("5. 1 item", 1 == jsonObject.length());
assertTrue("5. jsonObject found", jsonObject.get("tag1") instanceof JSONObject);
jsonObject = jsonObject.getJSONObject("tag1");
assertTrue("5. 2 contained items", 2 == jsonObject.length());
assertTrue("5. contained tag", "".equals(jsonObject.get("tag2")));
assertTrue("5. contained content jsonArray found", jsonObject.get("content") instanceof JSONArray);
jsonArray = jsonObject.getJSONArray("content");
assertTrue("5. array size", jsonArray.length() == 2);
assertTrue("5. content array entry 0", "val1".equals(jsonArray.get(0)));
assertTrue("5. content array entry 1", "val2".equals(jsonArray.get(1)));
/*
* If there is only 1 complex text content, then it is accumulated in a
* "content" field as a string.
*/
xmlStr = "<tag1>val1<tag2/></tag1>";
jsonObject = XML.toJSONObject(xmlStr);
assertTrue("6. 1 item", 1 == jsonObject.length());
assertTrue("6. jsonObject found", jsonObject.get("tag1") instanceof JSONObject);
jsonObject = jsonObject.getJSONObject("tag1");
assertTrue("6. contained content found", "val1".equals(jsonObject.get("content")));
assertTrue("6. contained tag2", "".equals(jsonObject.get("tag2")));
/*
* In this corner case, the content sibling happens to have key=content
* We end up with an array within an array, and no content element.
* This is probably a bug.
*/
xmlStr = "<tag1>val1<content/></tag1>";
jsonObject = XML.toJSONObject(xmlStr);
assertTrue("7. 1 item", 1 == jsonObject.length());
assertTrue("7. jsonArray found", jsonObject.get("tag1") instanceof JSONArray);
jsonArray = jsonObject.getJSONArray("tag1");
assertTrue("array size 1", jsonArray.length() == 1);
assertTrue("7. contained array found", jsonArray.get(0) instanceof JSONArray);
jsonArray = jsonArray.getJSONArray(0);
assertTrue("7. inner array size 2", jsonArray.length() == 2);
assertTrue("7. inner array item 0", "val1".equals(jsonArray.get(0)));
assertTrue("7. inner array item 1", "".equals(jsonArray.get(1)));
/*
* Confirm behavior of original issue
*/
String jsonStr =
"{"+
"\"Profile\": {"+
"\"list\": {"+
"\"history\": {"+
"\"entries\": ["+
"{"+
"\"deviceId\": \"id\","+
"\"content\": {"+
"\"material\": ["+
"{"+
"\"stuff\": false"+
"}"+
"]"+
"}"+
"}"+
"]"+
"}"+
"}"+
"}"+
"}";
jsonObject = new JSONObject(jsonStr);
xmlStr = XML.toString(jsonObject);
/*
* This is the created XML. Looks like content was mistaken for
* complex (child node + text) XML.
* <Profile>
* <list>
* <history>
* <entries>
* <deviceId>id</deviceId>
* {&quot;material&quot;:[{&quot;stuff&quot;:false}]}
* </entries>
* </history>
* </list>
* </Profile>
*/
assertTrue("nothing to test here, see comment on created XML, above", true);
}
/**
* Convenience method, given an input string and expected result,
* convert to JSONObject and compare actual to expected result.
* @param xmlStr the string to parse
* @param expectedStr the expected JSON string
*/
private void compareStringToJSONObject(String xmlStr, String expectedStr) {
JSONObject expectedJsonObject = new JSONObject(expectedStr);
JSONObject jsonObject = XML.toJSONObject(xmlStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Convenience method, given an input string and expected result,
* convert to JSONObject via reader and compare actual to expected result.
* @param xmlStr the string to parse
* @param expectedStr the expected JSON string
*/
private void compareReaderToJSONObject(String xmlStr, String expectedStr) {
/*
* Commenting out this method until the JSON-java code is updated
* to support XML.toJSONObject(reader)
JSONObject expectedJsonObject = new JSONObject(expectedStr);
Reader reader = new StringReader(xmlStr);
JSONObject jsonObject = XML.toJSONObject(reader);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
*/
}
/**
* Convenience method, given an input string and expected result, convert to
* JSONObject via file and compare actual to expected result.
*
* @param xmlStr
* the string to parse
* @param expectedStr
* the expected JSON string
* @throws IOException
*/
private void compareFileToJSONObject(String xmlStr, String expectedStr) {
/*
* Commenting out this method until the JSON-java code is updated
* to support XML.toJSONObject(reader)
try {
JSONObject expectedJsonObject = new JSONObject(expectedStr);
File tempFile = testFolder.newFile("fileToJSONObject.xml");
FileWriter fileWriter = new FileWriter(tempFile);
fileWriter.write(xmlStr);
fileWriter.close();
Reader reader = new FileReader(tempFile);
JSONObject jsonObject = XML.toJSONObject(reader);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
} catch (IOException e) {
assertTrue("file writer error: " +e.getMessage(), false);
}
*/
}
}