What you are trying to do is also called as Xpath in technical terms. It is used for html, xml based languages as well as now available in json

You can try jsonpath for this case:

https://www.baeldung.com/guide-to-jayway-jsonpath https://github.com/json-path/JsonPath

Answer from swapyonubuntu on Stack Overflow
Top answer
1 of 5
14

Java JsonPath API found at jayway JsonPath might have changed a little since all the above answers/comments. Documentation too. Just follow the above link and read that README.md, it contains some very clear usage documentation IMO.

Basically, as of current latest version 2.2.0 of the library, there are a few different ways of achieving what's been requested here, such as:

Pattern:
--------
String json = "{...your JSON here...}";
String jsonPathExpression = "$...your jsonPath expression here..."; 
J requestedClass = JsonPath.parse(json).read(jsonPathExpression, YouRequestedClass.class);

Example:
--------
// For better readability:  {"store": { "books": [ {"author": "Stephen King", "title": "IT"}, {"author": "Agatha Christie", "title": "The ABC Murders"} ] } }
String json = "{\"store\": { \"books\": [ {\"author\": \"Stephen King\", \"title\": \"IT\"}, {\"author\": \"Agatha Christie\", \"title\": \"The ABC Murders\"} ] } }";
String jsonPathExpression = "$.store.books[?(@.title=='IT')]"; 
JsonNode jsonNode = JsonPath.parse(json).read(jsonPathExpression, JsonNode.class);

And for reference, calling 'JsonPath.parse(..)' will return an object of class 'JsonContent' implementing some interfaces such as 'ReadContext', which contains several different 'read(..)' operations, such as the one demonstrated above:

/**
 * Reads the given path from this context
 *
 * @param path path to apply
 * @param type    expected return type (will try to map)
 * @param <T>
 * @return result
 */
<T> T read(JsonPath path, Class<T> type);

Hope this help anyone.

2 of 5
11

There definitely exists a way to query Json and get Json back using JsonPath. See example below:

 String jsonString = "{\"delivery_codes\": [{\"postal_code\": {\"district\": \"Ghaziabad\", \"pin\": 201001, \"pre_paid\": \"Y\", \"cash\": \"Y\", \"pickup\": \"Y\", \"repl\": \"N\", \"cod\": \"Y\", \"is_oda\": \"N\", \"sort_code\": \"GB\", \"state_code\": \"UP\"}}]}";
 String jsonExp = "$.delivery_codes";
 JsonNode pincodes = JsonPath.read(jsonExp, jsonString, JsonNode.class);
 System.out.println("pincodesJson : "+pincodes);

The output of the above will be inner Json.

[{"postal_code":{"district":"Ghaziabad","pin":201001,"pre_paid":"Y","cash":"Y","pickup":"Y","repl":"N","cod":"Y","is_oda":"N","sort_code":"GB","state_code":"UP"}}]

Now each individual name/value pairs can be parsed by iterating the List (JsonNode) we got above.

for(int i = 0; i< pincodes.size();i++){
    JsonNode node = pincodes.get(i);
    String pin = JsonPath.read("$.postal_code.pin", node, String.class);
    String district = JsonPath.read("$.postal_code.district", node, String.class);
    System.out.println("pin :: " + pin + " district :: " + district );
}

The output will be:

pin :: 201001 district :: Ghaziabad

Depending upon the Json you are trying to parse, you can decide whether to fetch a List or just a single String/Long value.

Hope it helps in solving your problem.

🌐
GitHub
github.com › json-path › JsonPath › blob › master › json-path › src › main › java › com › jayway › jsonpath › spi › json › JacksonJsonNodeJsonProvider.java
JsonPath/json-path/src/main/java/com/jayway/jsonpath/spi/json/JacksonJsonNodeJsonProvider.java at master · json-path/JsonPath
June 6, 2022 - if (!(obj instanceof JsonNode)) { throw new JsonPathException("Not a JSON Node"); } return obj.toString(); } · @Override · public Object createArray() { return JsonNodeFactory.instance.arrayNode(); } ·
Author   json-path
🌐
GitHub
github.com › json-path › JsonPath › blob › master › json-path › src › test › java › com › jayway › jsonpath › JacksonJsonNodeJsonProviderTest.java
JsonPath/json-path/src/test/java/com/jayway/jsonpath/JacksonJsonNodeJsonProviderTest.java at master · json-path/JsonPath
package com.jayway.jsonpath; · import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.jsonpath.spi.mapper.MappingException; import java.nio.charset.StandardCharsets; ·
Author   json-path
🌐
Jenkov
jenkov.com › tutorials › java-json › jackson-jsonnode.html
Jackson JsonNode
The Jackson JsonNode class is the Jackson tree object model for JSON. Jackson can read JSON into an object graph (tree) of JsonNode objects. Jackson can also write a JsonNode tree to JSON. This Jackson JsonNode tutorial explains how to work with the Jackson JsonNode class and its mutable subclass ...
🌐
Javadoc.io
javadoc.io › static › com.jayway.jsonpath › json-path › 2.4.0 › com › jayway › jsonpath › internal › filter › ValueNode.JsonNode.html
ValueNode.JsonNode (json-path 2.4.0 API)
com.jayway.jsonpath.internal.filter.ValueNode.JsonNode · Enclosing class: ValueNode · public static class ValueNode.JsonNode extends ValueNode ·
🌐
Literatejava
literatejava.com › uncategorized › using-jsonpath-safely-with-jacksons-jsonnode-tree-model
Using JsonPath safely with Jackson’s JsonNode tree model | Literate Java
June 12, 2025 - For these reasons, I generally recommend to wrap JayWay JsonPath usage within an application to help distinguish single-value from list semantics. While it’s possible to use a static helper, it’s better API to design an instantiated object which can hold context. ... import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.*; import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import java.util.Collections; import java.util.List; public class JsonP
Find elsewhere
🌐
Tabnine
tabnine.com › home page › code › java › com.fasterxml.jackson.databind.jsonnode
com.fasterxml.jackson.databind.JsonNode.path java code examples | Tabnine
private CoinbaseAddress getAddressFromNode(JsonNode addressNode) throws com.fasterxml.jackson.databind.exc.InvalidFormatException { final JsonNode nestedAddressNode = addressNode.path("address"); final String address = nestedAddressNode.path("address").asText(); final String callbackUrl = nestedAddressNode.path("callback_url").asText(); final String label = nestedAddressNode.path("label").asText(); final Date createdAt = DateUtils.fromISO8601DateString(nestedAddressNode.path("created_at").asText()); return new CoinbaseAddress(address, callbackUrl, label, createdAt); } }
Top answer
1 of 2
55
String json = "{\"firstName\":\"John\",\"lastName\":\"Doe\",\"address\":{\"street\":"
            + "\"21 2nd Street\",\"city\":\"New York\",\"postalCode\":\"10021-3100\","
            + "\"coordinates\":{\"latitude\":40.7250387,\"longitude\":-73.9932568}}}";

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
JsonNode coordinatesNode = node.at("/address/coordinates");

This is a JSON Pointer approach which I found here: https://cassiomolin.com/2016/07/13/using-jackson-and-json-pointer-to-query-and-parse-an-arbitrary-json-node/

2 of 2
54

The Jayway JsonPath library has support for reading values using a JSON path.

For example:

String json = "...";

Map<String, Object> book = JsonPath.read(json, "$.store.book[0]");
System.out.println(book);  // prints {category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}

Double price = JsonPath.read(json, "$.store.bicycle.price");
System.out.println(price);  // prints 19.95

You can also map JSON objects directly to classes, like in GSON or Jackson:

Book book = JsonPath.parse(json).read("$.store.book[0]", Book.class);
System.out.println(book);  // prints Book{category='reference', author='Nigel Rees', title='Sayings of the Century', price=8.95}

If you would like to specifically use GSON or Jackson to do the deserialization (the default is to use json-smart), you can also configure this:

Configuration.setDefaults(new Configuration.Defaults() {
    private final JsonProvider jsonProvider = new JacksonJsonProvider();
    private final MappingProvider mappingProvider = new JacksonMappingProvider();

    @Override
    public JsonProvider jsonProvider() {
        return jsonProvider;
    }

    @Override
    public MappingProvider mappingProvider() {
        return mappingProvider;
    }

    @Override
    public Set<Option> options() {
        return EnumSet.noneOf(Option.class);
    }
});

See the documentation for more details.

🌐
GitHub
github.com › json-everything › json-everything › issues › 406
Get (valid!) JsonPath or JsonPointer from a JsonNode · Issue #406 · json-everything/json-everything
March 16, 2023 - Json path generated by BCL's JsonNode.GetPath() for a property like $id is invalid and fails to be parsed by JsonPath.
Author   amis92
🌐
NodePit
nodepit.com › json path
JSON Path — NodePit
The result of a simple query (also called definite JSONPath) is a single value. The result of a collection query (also called indefinite JSONPath) is a list of multiple values. Results of JSONPath queries are converted to the selected KNIME type. If the result is a list and the selected KNIME type is not compatible, the execution will fail.
🌐
GitHub
github.com › json-path › JsonPath › issues › 160
Accept Jackson's JsonNode and return List<JsonNode> · Issue #160 · json-path/JsonPath
December 2, 2015 - json-path / JsonPath Public · Notifications · You must be signed in to change notification settings · Fork 1.7k · Star 9.3k · New issueCopy link · New issueCopy link · Closed · Closed · Accept Jackson's JsonNode and return List<JsonNode>#160 · Copy link · oleg-gr ·
Author   oleg-gr
🌐
Google Groups
groups.google.com › g › jsonpath › c › LuUI8XTvczs
Jackson JsonNode as input to JsonPath.read() not possible?
July 17, 2013 - From version 1.2.0 there is a new JsonProvider, the JacksonJsonNodeJsonProvider, that enables JsonNode based input and output. ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... Hi Kalle, I am looking for examples that show how to use JsonPath to query JsonNodes and get results back as JsonNodes.
🌐
Baeldung
baeldung.com › home › json › introduction to jsonpath
Introduction to JsonPath | Baeldung
November 13, 2023 - JsonPath uses special notation to represent nodes and their connections to adjacent nodes in a JsonPath path.