How to Build a Groovy‑Based JsonPath Utility Class
This article walks through the creation of a Groovy‑compatible JsonPath utility library, explaining its design, key methods for extracting various data types, a custom verification helper, and how to test it later with the Spock framework.
Overview
JsonUtil is a Groovy wrapper around the com.jayway.jsonpath.JsonPath library that simplifies extracting values from a JSON document. It is designed for Java/Groovy developers and provides typed getters for common primitive types, lists, and generic objects.
Key Features
Factory method JsonUtil.getInstance(JSONObject json) creates an instance.
Typed getters: getString, getInt, getBoolean, getLong, getDouble, getList, getT (generic).
Verification helper getVerify(String path) returns a Verify object for Groovy operator‑overloading based assertions.
All getters delegate to a private get(String path) method that invokes JsonPath.read.
Null or empty JSON triggers a custom ParamException. JsonPath parsing errors are caught and logged, returning null.
Implementation Details
The class extends SourceCode and holds a com.alibaba.fastjson.JSONObject instance. Logging is performed with SLF4J.
Example of the internal get method:
Object get(String path) {
logger.debug("Matching object: {}, expression: {}", json.toString(), path);
if (json == null || json.isEmpty())
ParamException.fail("json is null or empty");
try {
return JsonPath.read(this.json, path);
} catch (JsonPathException e) {
logger.warn("jsonpath:{} parsing failed, json value", json.toString(), path, e);
return null;
}
}Typed getters convert the raw value to the requested type using helper methods such as changeStringToInt, changeStringToBoolean, etc. The generic getter getT(String path, Class<T> tClass) attempts a cast and logs a warning on ClassCastException.
Usage Example
import com.alibaba.fastjson.JSONObject;
import com.fun.utils.JsonUtil;
def json = new JSONObject();
json.put("store", [book: [[author: "John"], [author: "Jane"]]]);
def util = JsonUtil.getInstance(json);
String author0 = util.getString('$.store.book[0].author'); // "John"
int count = util.getInt('$.store.book.size()');
List authors = util.getList('$.store.book[*].author');Dependencies
com.jayway.jsonpath:json-path– provides the JsonPath evaluation engine. com.alibaba.fastjson:fastjson – JSON object representation.
SLF4J for logging.
Future Work
Unit tests are planned using the Groovy‑based Spock framework to verify each getter and the verification helper.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
