From 56be31e7a83223162a29e51f2daaa9eb9ad2de3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Mon, 16 May 2016 14:53:34 +0200 Subject: [PATCH] fixing stleary/JSON-Java#233 --- JSONArray.java | 17 +++++++++++++++++ JSONObject.java | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/JSONArray.java b/JSONArray.java index f338a2d..4ddd1cd 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -963,6 +963,23 @@ public class JSONArray implements Iterable { public Object query(String jsonPointer) { return new JSONPointer(jsonPointer).queryFrom(this); } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param jsonPointer the string representation of the JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(String jsonPointer) { + JSONPointer pointer = new JSONPointer(jsonPointer); + try { + return pointer.queryFrom(this); + } catch (JSONPointerException e) { + return null; + } + } /** * Remove an index and close the hole. diff --git a/JSONObject.java b/JSONObject.java index ab113f3..e3f2270 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1341,6 +1341,23 @@ public class JSONObject { public Object query(String jsonPointer) { return new JSONPointer(jsonPointer).queryFrom(this); } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param jsonPointer the string representation of the JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(String jsonPointer) { + JSONPointer pointer = new JSONPointer(jsonPointer); + try { + return pointer.queryFrom(this); + } catch (JSONPointerException e) { + return null; + } + } /** * Produce a string in double quotes with backslash sequences in all the