Quantcast
Viewing latest article 1
Browse Latest Browse All 2

Answer by LHCHIN for How to get dynamic JSON Value by Key without parsing to Java Object?

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


Viewing latest article 1
Browse Latest Browse All 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>