Skip to content

Commit f91d0c8

Browse files
committed
New JSONObject.optJSONObject method with defaultValue parameter
1 parent 4571978 commit f91d0c8

2 files changed

Lines changed: 18 additions & 6 deletions

File tree

src/main/java/org/json/JSONObject.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1370,9 +1370,21 @@ public JSONArray optJSONArray(String key) {
13701370
* A key string.
13711371
* @return A JSONObject which is the value.
13721372
*/
1373-
public JSONObject optJSONObject(String key) {
1373+
public JSONObject optJSONObject(String key) { return this.optJSONObject(key, null); }
1374+
1375+
/**
1376+
* Get an optional JSONObject associated with a key, or the default if there
1377+
* is no such key or if the value is not a JSONObject.
1378+
*
1379+
* @param key
1380+
* A key string.
1381+
* @param defaultValue
1382+
* The default.
1383+
* @return An JSONObject which is the value.
1384+
*/
1385+
public JSONObject optJSONObject(String key, JSONObject defaultValue) {
13741386
Object object = this.opt(key);
1375-
return object instanceof JSONObject ? (JSONObject) object : null;
1387+
return object instanceof JSONObject ? (JSONObject) object : defaultValue;
13761388
}
13771389

13781390
/**

src/test/java/org/json/junit/JSONObjectTest.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2404,8 +2404,8 @@ public void jsonObjectOptDefault() {
24042404
MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1)));
24052405
assertTrue("optJSONArray() should return null ",
24062406
null==jsonObject.optJSONArray("myKey"));
2407-
assertTrue("optJSONObject() should return null ",
2408-
null==jsonObject.optJSONObject("myKey"));
2407+
assertTrue("optJSONObject() should return default JSONObject ",
2408+
jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey").equals("testValue"));
24092409
assertTrue("optLong() should return default long",
24102410
42l == jsonObject.optLong("myKey", 42l));
24112411
assertTrue("optDouble() should return default double",
@@ -2440,8 +2440,8 @@ public void jsonObjectOptNoKey() {
24402440
MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1)));
24412441
assertTrue("optJSONArray() should return null ",
24422442
null==jsonObject.optJSONArray("myKey"));
2443-
assertTrue("optJSONObject() should return null ",
2444-
null==jsonObject.optJSONObject("myKey"));
2443+
assertTrue("optJSONObject() should return default JSONObject ",
2444+
jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey").equals("testValue"));
24452445
assertTrue("optLong() should return default long",
24462446
42l == jsonObject.optLong("myKey", 42l));
24472447
assertTrue("optDouble() should return default double",

0 commit comments

Comments
 (0)