Skip to content

Commit 56be31e

Browse files
committed
fixing stleary#233
1 parent c044eb1 commit 56be31e

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
@@ -963,6 +963,23 @@ public JSONArray put(int index, Object value) throws JSONException {
963963
public Object query(String jsonPointer) {
964964
return new JSONPointer(jsonPointer).queryFrom(this);
965965
}
966+
967+
/**
968+
* Queries and returns a value from this object using {@code jsonPointer}, or
969+
* returns null if the query fails due to a missing key.
970+
*
971+
* @param jsonPointer the string representation of the JSON pointer
972+
* @return the queried value or {@code null}
973+
* @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
974+
*/
975+
public Object optQuery(String jsonPointer) {
976+
JSONPointer pointer = new JSONPointer(jsonPointer);
977+
try {
978+
return pointer.queryFrom(this);
979+
} catch (JSONPointerException e) {
980+
return null;
981+
}
982+
}
966983

967984
/**
968985
* Remove an index and close the hole.

JSONObject.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1341,6 +1341,23 @@ public JSONObject putOpt(String key, Object value) throws JSONException {
13411341
public Object query(String jsonPointer) {
13421342
return new JSONPointer(jsonPointer).queryFrom(this);
13431343
}
1344+
1345+
/**
1346+
* Queries and returns a value from this object using {@code jsonPointer}, or
1347+
* returns null if the query fails due to a missing key.
1348+
*
1349+
* @param jsonPointer the string representation of the JSON pointer
1350+
* @return the queried value or {@code null}
1351+
* @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
1352+
*/
1353+
public Object optQuery(String jsonPointer) {
1354+
JSONPointer pointer = new JSONPointer(jsonPointer);
1355+
try {
1356+
return pointer.queryFrom(this);
1357+
} catch (JSONPointerException e) {
1358+
return null;
1359+
}
1360+
}
13441361

13451362
/**
13461363
* Produce a string in double quotes with backslash sequences in all the

0 commit comments

Comments
 (0)