Skip to content

Commit 516729b

Browse files
committed
jsonpath with new use cases
1 parent 7011fa4 commit 516729b

5 files changed

Lines changed: 331 additions & 0 deletions

File tree

‎json-path/pom.xml‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>org.baeldung</groupId>
5+
<artifactId>json-path</artifactId>
6+
<version>0.0.1-SNAPSHOT</version>
7+
<name>json-path</name>
8+
9+
<dependencies>
10+
<!-- json-path -->
11+
<dependency>
12+
<groupId>com.jayway.jsonpath</groupId>
13+
<artifactId>json-path</artifactId>
14+
<version>${json-path.version}</version>
15+
</dependency>
16+
17+
<!-- Testing -->
18+
<dependency>
19+
<groupId>junit</groupId>
20+
<artifactId>junit</artifactId>
21+
<version>${junit.version}</version>
22+
<scope>test</scope>
23+
</dependency>
24+
25+
<!-- Logging -->
26+
<dependency>
27+
<groupId>org.slf4j</groupId>
28+
<artifactId>slf4j-api</artifactId>
29+
<version>${slf4j.version}</version>
30+
<scope>runtime</scope>
31+
</dependency>
32+
<dependency>
33+
<groupId>ch.qos.logback</groupId>
34+
<artifactId>logback-classic</artifactId>
35+
<version>${logback.version}</version>
36+
<scope>runtime</scope>
37+
</dependency>
38+
</dependencies>
39+
40+
<properties>
41+
<!-- json-path -->
42+
<json-path.version>2.1.0</json-path.version>
43+
44+
<!-- Testing -->
45+
<junit.version>4.12</junit.version>
46+
47+
<!-- Logging -->
48+
<slf4j.version>1.7.14</slf4j.version>
49+
<logback.version>1.1.3</logback.version>
50+
</properties>
51+
</project>
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
{
2+
"tool":
3+
{
4+
"jsonpath":
5+
{
6+
"creator":
7+
{
8+
"name": "Jayway Inc.",
9+
"location":
10+
[
11+
"Malmo",
12+
"Stockholm",
13+
"Copenhagen",
14+
"San Francisco",
15+
"Karlskrona",
16+
"Halmstad",
17+
"Helsingborg"
18+
]
19+
},
20+
21+
"current release": "2.1"
22+
}
23+
},
24+
25+
"book":
26+
[
27+
{
28+
"title": "Beginning JSON",
29+
"author": "Ben Smith",
30+
"price": 49.99
31+
},
32+
33+
{
34+
"title": "JSON at Work",
35+
"author": "Tom Marrs",
36+
"price": 29.99
37+
},
38+
39+
{
40+
"title": "Learn JSON in a DAY",
41+
"author": "Acodemy",
42+
"price": 8.99
43+
},
44+
45+
{
46+
"title": "JSON: Questions and Answers",
47+
"author": "George Duckett",
48+
"price": 6.00
49+
}
50+
],
51+
52+
"price range":
53+
{
54+
"cheap": 10.00,
55+
"medium": 20.00
56+
}
57+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
[
2+
{
3+
"id": 1,
4+
"title": "Casino Royale",
5+
"director": "Martin Campbell",
6+
"starring":
7+
[
8+
"Daniel Craig",
9+
"Eva Green"
10+
],
11+
12+
"desc": "Twenty-first James Bond movie",
13+
"release date": 1163466000000,
14+
"box office": 594275385
15+
},
16+
17+
{
18+
"id": 2,
19+
"title": "Quantum of Solace",
20+
"director": "Marc Forster",
21+
"starring":
22+
[
23+
"Daniel Craig",
24+
"Olga Kurylenko"
25+
],
26+
27+
"desc": "Twenty-second James Bond movie",
28+
"release date": 1225242000000,
29+
"box office": 591692078
30+
},
31+
32+
{
33+
"id": 3,
34+
"title": "Skyfall",
35+
"director": "Sam Mendes",
36+
"starring":
37+
[
38+
"Daniel Craig",
39+
"Naomie Harris"
40+
],
41+
42+
"desc": "Twenty-third James Bond movie",
43+
"release date": 1350954000000,
44+
"box office": 1110526981
45+
},
46+
47+
{
48+
"id": 4,
49+
"title": "Spectre",
50+
"director": "Sam Mendes",
51+
"starring":
52+
[
53+
"Daniel Craig",
54+
"Lea Seydoux"
55+
],
56+
57+
"desc": "Twenty-fourth James Bond movie",
58+
"release date": 1445821200000,
59+
"box office": 879376275
60+
}
61+
]
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package org.baeldung.jsonpath.introduction;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertThat;
5+
import static org.hamcrest.CoreMatchers.containsString;
6+
import static org.hamcrest.CoreMatchers.not;
7+
8+
import org.junit.Test;
9+
10+
import java.io.InputStream;
11+
import java.util.List;
12+
import java.util.Map;
13+
import java.util.Scanner;
14+
15+
import com.jayway.jsonpath.Criteria;
16+
import com.jayway.jsonpath.DocumentContext;
17+
import com.jayway.jsonpath.Filter;
18+
import com.jayway.jsonpath.JsonPath;
19+
import com.jayway.jsonpath.Predicate;
20+
21+
public class OperationTest {
22+
InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json");
23+
String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
24+
25+
@Test
26+
public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() {
27+
String jsonpathCreatorNamePath = "$['tool']['jsonpath']['creator']['name']";
28+
String jsonpathCreatorLocationPath = "$['tool']['jsonpath']['creator']['location'][*]";
29+
30+
DocumentContext jsonContext = JsonPath.parse(jsonDataSourceString);
31+
String jsonpathCreatorName = jsonContext.read(jsonpathCreatorNamePath);
32+
List<String> jsonpathCreatorLocation = jsonContext.read(jsonpathCreatorLocationPath);
33+
34+
assertEquals("Jayway Inc.", jsonpathCreatorName);
35+
assertThat(jsonpathCreatorLocation.toString(), containsString("Malmo"));
36+
assertThat(jsonpathCreatorLocation.toString(), containsString("San Francisco"));
37+
assertThat(jsonpathCreatorLocation.toString(), containsString("Helsingborg"));
38+
}
39+
40+
@Test
41+
public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() {
42+
Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00));
43+
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter);
44+
predicateUsageAssertionHelper(expensive);
45+
}
46+
47+
@Test
48+
public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() {
49+
Predicate expensivePredicate = new Predicate() {
50+
public boolean apply(PredicateContext context) {
51+
String value = context.item(Map.class).get("price").toString();
52+
return Float.valueOf(value) > 20.00;
53+
}
54+
};
55+
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate);
56+
predicateUsageAssertionHelper(expensive);
57+
}
58+
59+
@Test
60+
public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() {
61+
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?(@['price'] > $['price range']['medium'])]");
62+
predicateUsageAssertionHelper(expensive);
63+
}
64+
65+
private void predicateUsageAssertionHelper(List<?> predicate) {
66+
assertThat(predicate.toString(), containsString("Beginning JSON"));
67+
assertThat(predicate.toString(), containsString("JSON at Work"));
68+
assertThat(predicate.toString(), not(containsString("Learn JSON in a DAY")));
69+
assertThat(predicate.toString(), not(containsString("JSON: Questions and Answers")));
70+
}
71+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package org.baeldung.jsonpath.introduction;
2+
3+
import static org.junit.Assert.assertThat;
4+
import static org.junit.Assert.assertEquals;
5+
import static org.hamcrest.CoreMatchers.containsString;
6+
7+
import org.junit.Test;
8+
9+
import java.io.InputStream;
10+
import java.util.ArrayList;
11+
import java.util.Arrays;
12+
import java.util.List;
13+
import java.util.Map;
14+
import java.util.Scanner;
15+
16+
import com.jayway.jsonpath.Configuration;
17+
import com.jayway.jsonpath.DocumentContext;
18+
import com.jayway.jsonpath.JsonPath;
19+
import com.jayway.jsonpath.Option;
20+
21+
public class ServiceTest {
22+
InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json");
23+
String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
24+
25+
@Test
26+
public void givenId_whenRequestingRecordData_thenSucceed() {
27+
Object dataObject = JsonPath.parse(jsonString).read("$[?(@.id == 2)]");
28+
String dataString = dataObject.toString();
29+
30+
assertThat(dataString, containsString("2"));
31+
assertThat(dataString, containsString("Quantum of Solace"));
32+
assertThat(dataString, containsString("Twenty-second James Bond movie"));
33+
}
34+
35+
@Test
36+
public void givenStarring_whenRequestingMovieTitle_thenSucceed() {
37+
List<Map<String, Object>> dataList = JsonPath.parse(jsonString).read("$[?('Eva Green' in @['starring'])]");
38+
String title = (String) dataList.get(0).get("title");
39+
40+
assertEquals("Casino Royale", title);
41+
}
42+
43+
@Test
44+
public void givenCompleteStructure_whenCalculatingTotalRevenue_thenSucceed() {
45+
DocumentContext context = JsonPath.parse(jsonString);
46+
int length = context.read("$.length()");
47+
long revenue = 0;
48+
for (int i = 0; i < length; i++) {
49+
revenue += context.read("$[" + i + "]['box office']", Long.class);
50+
}
51+
52+
assertEquals(594275385L + 591692078L + 1110526981L + 879376275L, revenue);
53+
}
54+
55+
@Test
56+
public void givenStructure_whenRequestingHighestRevenueMovieTitle_thenSucceed() {
57+
DocumentContext context = JsonPath.parse(jsonString);
58+
List<Object> revenueList = context.read("$[*]['box office']");
59+
Integer[] revenueArray = revenueList.toArray(new Integer[0]);
60+
Arrays.sort(revenueArray);
61+
62+
int highestRevenue = revenueArray[revenueArray.length - 1];
63+
Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build();
64+
List<String> pathList = JsonPath.using(pathConfiguration).parse(jsonString).read("$[?(@['box office'] == " + highestRevenue + ")]");
65+
66+
Map<String, String> dataRecord = context.read(pathList.get(0));
67+
String title = dataRecord.get("title");
68+
69+
assertEquals("Skyfall", title);
70+
}
71+
72+
@Test
73+
public void givenDirector_whenRequestingLatestMovieTitle_thenSucceed() {
74+
DocumentContext context = JsonPath.parse(jsonString);
75+
List<Map<String, Object>> dataList = context.read("$[?(@.director == 'Sam Mendes')]");
76+
77+
List<Object> dateList = new ArrayList<>();
78+
for (Map<String, Object> item : dataList) {
79+
Object date = item.get("release date");
80+
dateList.add(date);
81+
}
82+
Long[] dateArray = dateList.toArray(new Long[0]);
83+
Arrays.sort(dateArray);
84+
85+
long latestTime = dateArray[dateArray.length - 1];
86+
List<Map<String, Object>> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]");
87+
String title = (String) finalDataList.get(0).get("title");
88+
89+
assertEquals("Spectre", title);
90+
}
91+
}

0 commit comments

Comments
 (0)