mirror of
https://github.com/stleary/JSON-java.git
synced 2025-08-03 03:15:32 -04:00
Merge pull request #610 from tilds/optJSONObject-defaultValue
New JSONObject.optJSONObject method with defaultValue parameter
This commit is contained in:
commit
449ec8745e
@ -1370,9 +1370,21 @@ public class JSONObject {
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -2404,8 +2404,8 @@ public class JSONObjectTest {
|
||||
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",
|
||||
@ -2440,8 +2440,8 @@ public class JSONObjectTest {
|
||||
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",
|
||||
|
Loading…
x
Reference in New Issue
Block a user