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