How to Build a JSON DSL in Spring Boot with Jayway JsonPath

This tutorial demonstrates adding JsonPath to a Spring Boot project, using DSL‑style expressions to extract authors, titles, counts and filtered data from a sample JSON payload, and shows how to drive the extraction dynamically via configurable mappings with fastjson and hutool.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
How to Build a JSON DSL in Spring Boot with Jayway JsonPath

Scenario

After setting up a RuoYi Spring Boot project (referencing the linked CSDN guide) and adding the required libraries—fastjson, hutool and com.jayway.jsonpath:json-path:2.8.0 —the article explains how to treat Jayway JsonPath as a DSL for reading JSON documents returned by third‑party APIs.

Sample JSON

{
  "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},
      {"category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99}
    ],
    "bicycle": {"color": "red", "price": 19.95}
  },
  "expensive": 10
}

Quick start examples

Read all author fields:

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

Read the title of the first book (two equivalent expressions):

String title = JsonPath.read(body, "$['store']['book'][0]['title']");
String title2 = JsonPath.read(body, "$.store.book[0].title");

Get the total number of books: Integer number = JsonPath.read(body, "$..book.length()"); Filter books with price greater than 10:

List<Map<String, Object>> expensiveBooks = JsonPath.read(body, "$.store.book[?(@.price > 10)]");

Dynamic extraction via configurable mapping

The article shows how to first obtain the book count, then iterate and use a JSON mapping that stores JsonPath expressions with placeholders. The mapping is parsed with fastjson:

int dataSize = JsonPath.read(body, "$..book.length()");
JSONObject mapping = JSON.parseObject("{\"title\":\"$.store.book[%d].title\",\"author\":\"$.store.book[%d].author\"}");
for (int i = 0; i < dataSize; i++) {
    String titleName = mapping.containsKey("title") ? JsonPath.read(body, String.format(mapping.getString("title"), i)).toString() : null;
    System.out.println(titleName);
    String author = mapping.containsKey("author") ? JsonPath.read(body, String.format(mapping.getString("author"), i)).toString() : null;
    System.out.println(author);
}

Complete unit‑test example

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RuoYiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class JsonPathTest {
    @Test
    public void getData() {
        String body = "";
        try {
            // Simulate fetching API data
            body = HttpRequest.get("http://127.0.0.1:4523/m1/2858210-0-default/testJsonPath")
                             .timeout(20000)
                             .execute()
                             .body();
            // All authors
            List<String> authors = JsonPath.read(body, "$.store.book[*].author");
            System.out.println(authors);
            // First book title (two ways)
            String title = JsonPath.read(body, "$['store']['book'][0]['title']");
            String title2 = JsonPath.read(body, "$.store.book[0].title");
            System.out.println(title);
            System.out.println(title2);
            // Book count
            Integer number = JsonPath.read(body, "$..book.length()");
            System.out.println(number);
            // Books priced > 10
            List<Map<String, Object>> expensiveBooks = JsonPath.read(body, "$.store.book[?(@.price > 10)]");
            System.out.println(expensiveBooks);
            // Dynamic extraction based on mapping
            int dataSize = JsonPath.read(body, "$..book.length()");
            JSONObject mapping = JSON.parseObject("{\"title\":\"$.store.book[%d].title\",\"author\":\"$.store.book[%d].author\"}");
            for (int i = 0; i < dataSize; i++) {
                String titleName = mapping.containsKey("title") ? JsonPath.read(body, String.format(mapping.getString("title"), i)).toString() : null;
                System.out.println(titleName);
                String author = mapping.containsKey("author") ? JsonPath.read(body, String.format(mapping.getString("author"), i)).toString() : null;
                System.out.println(author);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Test result

Unit test output
Unit test output

The article concludes that JsonPath provides a concise, XPath‑like syntax for navigating JSON structures, and by storing expressions in configuration one can dynamically extract arbitrary fields without hard‑coding paths.

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.

JavaDSLspring-bootfastjsonhutoolJsonPathjson-parsing
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

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.