Skip to content

Commit

Permalink
Merge pull request #610 from tilds/optJSONObject-defaultValue
Browse files Browse the repository at this point in the history
New JSONObject.optJSONObject method with defaultValue parameter
  • Loading branch information
stleary committed Jun 29, 2021
2 parents 4571978 + f91d0c8 commit 449ec87
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
16 changes: 14 additions & 2 deletions src/main/java/org/json/JSONObject.java
Expand Up @@ -1370,9 +1370,21 @@ public JSONArray optJSONArray(String key) {
* A key string.
* @return A JSONObject which is the value.
*/
public JSONObject optJSONObject(String key) {
public JSONObject optJSONObject(String key) { return this.optJSONObject(key, null); }

/**
* Get an optional JSONObject associated with a key, or the default if there
* is no such key or if the value is not a JSONObject.
*
* @param key
* A key string.
* @param defaultValue
* The default.
* @return An JSONObject which is the value.
*/
public JSONObject optJSONObject(String key, JSONObject defaultValue) {
Object object = this.opt(key);
return object instanceof JSONObject ? (JSONObject) object : null;
return object instanceof JSONObject ? (JSONObject) object : defaultValue;
}

/**
Expand Down
8 changes: 4 additions & 4 deletions src/test/java/org/json/junit/JSONObjectTest.java
Expand Up @@ -2404,8 +2404,8 @@ public void jsonObjectOptDefault() {
MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1)));
assertTrue("optJSONArray() should return null ",
null==jsonObject.optJSONArray("myKey"));
assertTrue("optJSONObject() should return null ",
null==jsonObject.optJSONObject("myKey"));
assertTrue("optJSONObject() should return default JSONObject ",
jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey").equals("testValue"));
assertTrue("optLong() should return default long",
42l == jsonObject.optLong("myKey", 42l));
assertTrue("optDouble() should return default double",
Expand Down Expand Up @@ -2440,8 +2440,8 @@ public void jsonObjectOptNoKey() {
MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1)));
assertTrue("optJSONArray() should return null ",
null==jsonObject.optJSONArray("myKey"));
assertTrue("optJSONObject() should return null ",
null==jsonObject.optJSONObject("myKey"));
assertTrue("optJSONObject() should return default JSONObject ",
jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey").equals("testValue"));
assertTrue("optLong() should return default long",
42l == jsonObject.optLong("myKey", 42l));
assertTrue("optDouble() should return default double",
Expand Down

0 comments on commit 449ec87

Please sign in to comment.