Master JSONPath in Spring Boot: Simplify Complex JSON Extraction

JSONPath offers a concise, XPath‑like syntax for extracting data from complex JSON structures, and this guide shows how to integrate it into Spring Boot, compare FastJSON, Jackson, and Gson implementations, and provides practical code examples, advanced configurations, and selection advice for Java projects.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Master JSONPath in Spring Boot: Simplify Complex JSON Extraction

What is JSONPath?

JSONPath is a query language for extracting data from JSON documents, using a syntax similar to JavaScript object access.

Common JSONPath syntax

$

– root node @ – current node . or [] – child operator .. – recursive descent * – wildcard (matches all members/elements) [] – array index [start:end] – array slice [?()] – filter expression

Spring Boot integration

Dependency

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.9.0</version>
</dependency>

Basic usage example

Given the following JSON document:

{
  "store": {
    "book": [
      { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 },
      { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 },
      { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }
    ],
    "bicycle": { "color": "red", "price": 19.95 }
  }
}

Reading data with JSONPath:

List<String> authors = JsonPath.parse(json)
    .read("$.store.book[*].author");

Double price = JsonPath.parse(json)
    .read("$.store.book[0].price");

List<Map> cheapBooks = JsonPath.parse(json)
    .read("$.store.book[?(@.price < 10)]");

Advanced usage

Custom configuration

@Configuration
public class JsonPathConfig {
    public Configuration jsonPathConfiguration() {
        return Configuration.builder()
            .options(Option.SUPPRESS_EXCEPTIONS)
            .options(Option.DEFAULT_PATH_LEAF_TO_NULL)
            .options(Option.ALWAYS_RETURN_LIST)
            .options(Option.CACHE)
            .build();
    }
}

Cache parsing results

@Service
public class JsonPathCacheService {
    private final Map<String, Object> cache = new ConcurrentHashMap<>();

    public Object readWithCache(String json, String path) {
        return JsonPath.using(Configuration.defaultConfiguration())
            .parse(json)
            .read(path);
    }

    private final JsonPath compiledPath = JsonPath.compile("$.store.book[*]");

    public List<Map> readOptimized(String json) {
        return compiledPath.read(json);
    }
}

Combine with REST calls

@Service
public class ExternalApiService {
    private final RestTemplate restTemplate;

    public List<String> extractFromExternalApi(String url, String jsonPath) {
        String response = restTemplate.getForObject(url, String.class);
        return JsonPath.parse(response).read(jsonPath);
    }
}

FastJSON built‑in JSONPath

Dependency

<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.53</version>
</dependency>

Usage example

JSONObject object = JSON.parseObject(json);
List<String> authors = (List<String>) JSONPath.eval(object, "$.store.book[*].author");
Double price = (Double) JSONPath.eval(object, "$.store.book[0].price");
List books = (List) JSONPath.eval(object, "$.store.book[?(@.price < 10)]");

Modification operations

JSONPath.set(object, "$.store.book[0].price", 99.99);
JSONPath.set(object, "$.store.bicycle.color", "blue");
JSONPath.set(object, "$.store.book[*].price", 15.88);
JSONPath.set(object, "$.store.book[?(@.isbn)].category", "classic");
JSONPath.set(object, "$.store.book[0].publisher", "Tech Press");
JSONArray bookArray = (JSONArray) JSONPath.eval(object, "$.store.book");
bookArray.add(JSON.parseObject("{\"title\":\"New Book\",\"price\":9.99}"));
JSONPath.remove(object, "$.store.bicycle");

Jackson support

JsonPointer (RFC 6901)

JsonNode root = mapper.readTree(json);
JsonPointer ptr = JsonPointer.compile("/store/book/0/author");
String author = root.at(ptr).asText();
String title = root.at("/store/book/1/title").asText();
Double price = root.at("/store/bicycle/price").asDouble();

Jackson‑JsonPath (third‑party)

Configuration configuration = Configuration.builder()
    .jsonProvider(new JacksonJsonNodeJsonProvider())
    .mappingProvider(new JacksonMappingProvider())
    .build();

List<String> authors = JsonPath.using(configuration)
    .parse(json)
    .read("$.store.book[*].author");

Gson

Gson does not include JSONPath; it is usually combined with Jayway JsonPath for advanced queries.

List<String> authors = JsonPath.parse(json)
    .read("$.store.book[*].author");
JsonElement element = gson.toJsonTree(authors);

Solution comparison

FastJSON – native JSONPath, supports wildcards and filters, excellent performance, but has had security issues.

Jackson + JsonPointer – built‑in, very stable, but limited to simple paths.

Jackson + Jayway JsonPath – full JSONPath support, requires an extra dependency.

Gson – no native support; pair with Jayway JsonPath when needed.

Selection recommendations

Existing FastJSON projects: use FastJSON’s JSONPath directly.

Jackson‑based projects: simple cases use JsonPointer; complex cases add Jayway JsonPath.

Gson projects: pair Gson with Jayway JsonPath.

New projects: prefer Jackson together with Jayway JsonPath for a balanced solution.

Conclusion

JSONPath simplifies extraction, filtering, and dynamic queries on JSON data. Integrating it into Spring Boot reduces boilerplate code and improves readability, making it a practical choice for handling complex JSON structures and third‑party API responses in Java applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootFastJSONGsonjacksonJSONPath
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.