Add optJSONArray method to JSONObject with a default value

This commit is contained in:
Edijs 2023-09-25 20:18:33 +03:00
parent 74cd73f97c
commit db0fde2a56
2 changed files with 20 additions and 2 deletions

View File

@ -1512,8 +1512,22 @@ public class JSONObject {
* @return A JSONArray which is the value.
*/
public JSONArray optJSONArray(String key) {
Object o = this.opt(key);
return o instanceof JSONArray ? (JSONArray) o : null;
return this.optJSONArray(key, null);
}
/**
* Get an optional JSONArray associated with a key, or the default if there
* is no such key, or if its value is not a JSONArray.
*
* @param key
* A key string.
* @param defaultValue
* The default.
* @return A JSONArray which is the value.
*/
public JSONArray optJSONArray(String key, JSONArray defaultValue) {
Object object = this.opt(key);
return object instanceof JSONArray ? (JSONArray) object : defaultValue;
}
/**

View File

@ -2510,6 +2510,8 @@ public class JSONObjectTest {
MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1)));
assertTrue("optJSONArray() should return null ",
null==jsonObject.optJSONArray("myKey"));
assertTrue("optJSONArray() should return default JSONArray",
"value".equals(jsonObject.optJSONArray("myKey", new JSONArray("[\"value\"]")).getString(0)));
assertTrue("optJSONObject() should return default JSONObject ",
jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey").equals("testValue"));
assertTrue("optLong() should return default long",
@ -2555,6 +2557,8 @@ public class JSONObjectTest {
Integer.valueOf(42).equals(jsonObject.optIntegerObject("myKey", 42)));
assertTrue("optEnum() should return default Enum",
MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1)));
assertTrue("optJSONArray() should return default JSONArray",
"value".equals(jsonObject.optJSONArray("myKey", new JSONArray("[\"value\"]")).getString(0)));
assertTrue("optJSONArray() should return null ",
null==jsonObject.optJSONArray("myKey"));
assertTrue("optJSONObject() should return default JSONObject ",