Skip to content

Commit b2bde1f

Browse files
committed
Merge pull request stleary#234 from erosb/master
fixing stleary#233
2 parents 9a81b40 + 56be31e commit b2bde1f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

JSONArray.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -982,6 +982,23 @@ public JSONArray put(int index, Object value) throws JSONException {
982982
public Object query(String jsonPointer) {
983983
return new JSONPointer(jsonPointer).queryFrom(this);
984984
}
985+
986+
/**
987+
* Queries and returns a value from this object using {@code jsonPointer}, or
988+
* returns null if the query fails due to a missing key.
989+
*
990+
* @param jsonPointer the string representation of the JSON pointer
991+
* @return the queried value or {@code null}
992+
* @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
993+
*/
994+
public Object optQuery(String jsonPointer) {
995+
JSONPointer pointer = new JSONPointer(jsonPointer);
996+
try {
997+
return pointer.queryFrom(this);
998+
} catch (JSONPointerException e) {
999+
return null;
1000+
}
1001+
}
9851002

9861003
/**
9871004
* Remove an index and close the hole.

JSONObject.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1360,6 +1360,23 @@ public JSONObject putOpt(String key, Object value) throws JSONException {
13601360
public Object query(String jsonPointer) {
13611361
return new JSONPointer(jsonPointer).queryFrom(this);
13621362
}
1363+
1364+
/**
1365+
* Queries and returns a value from this object using {@code jsonPointer}, or
1366+
* returns null if the query fails due to a missing key.
1367+
*
1368+
* @param jsonPointer the string representation of the JSON pointer
1369+
* @return the queried value or {@code null}
1370+
* @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
1371+
*/
1372+
public Object optQuery(String jsonPointer) {
1373+
JSONPointer pointer = new JSONPointer(jsonPointer);
1374+
try {
1375+
return pointer.queryFrom(this);
1376+
} catch (JSONPointerException e) {
1377+
return null;
1378+
}
1379+
}
13631380

13641381
/**
13651382
* Produce a string in double quotes with backslash sequences in all the

0 commit comments

Comments
 (0)