Q: How to get dynamic JSON Value by Key without parsing to Java Object? I am trying to get a json(has unknown template) value with a dynamic key like;
"user.specs.id"

Problem is my json structure is not static and because of this I can't parse it to a java Object or get its properties with Gson methods.
{
    "user": {
        "specs": {
            "id": 12222,
            "name": "foo"
        } 
    }
}

Is there a way to extract some data from any json with some key?
EDIT: I have a service method like;
public Object getValueByKey(String json, String key);

possible values for "json" param;
{"name": "test"}    //possible key "name"

{"user": {"id": 1232}}   //possible key "user.id"

{"cars": ["car1", "car2"]}   //possible key "cars[0]"


A: As @Michał Ziober's comment, you can simply achieve this by using JsonPath as follows:
Maven dependency
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

Code snippet
public static void main(String[] args) {
    getValueByKey("{\"name\": \"test\"}", "name");
    getValueByKey("{\"user\": {\"id\": 1232}}", "user.id");
    getValueByKey("{\"cars\": [\"car1\", \"car2\"]}", "cars[0]");
}

public static void getValueByKey(String json, String key) {
    DocumentContext jsonContext = JsonPath.parse(json);
    Object value = jsonContext.read(key);
    System.out.println(value.toString());
}

Console output

11:38:50.840 [main] DEBUG c.j.j.internal.path.CompiledPath - Evaluating path: $['name']
  test
  11:38:50.855 [main] DEBUG c.j.j.internal.path.CompiledPath - Evaluating path: $['user']['id']
  1232
  11:38:50.855 [main] DEBUG c.j.j.internal.path.CompiledPath - Evaluating path: $['cars'][0]
  car1


Read more


*

*JsonPath

*Introduction to JsonPath
