1 回答

TA贡献1786条经验 获得超11个赞
按照 上的文档https://github.com/json-path/JsonPath,这应该给你你正在寻找的东西。
List output = JsonPath.read(json, "$.books[*].['book_id', 'reviews'])");
看看这个测试用例。
@Test
final void test2() {
String json = "{ \"books\": ["
+ " {"
+ " \"category\": \"reference\","
+ " \"author\": \"Nigel Rees\","
+ " \"book_id\": \"214515\","
+ " \"title\": \"Sayings of the Century\","
+ " \"price\": 8.95,"
+ " \"reviews\": ["
+ " {"
+ " \"rating\": 2,"
+ " \"reviewer\": \"Amazon\","
+ " \"weight\": 0"
+ " }"
+ " ]"
+ " },"
+ " {"
+ " \"category\": \"reference\","
+ " \"author\": \"Nigel Rees\","
+ " \"book_id\": \"314515\","
+ " \"title\": \"Sayings of the Century\","
+ " \"price\": 8.95,"
+ " \"reviews\": ["
+ " {"
+ " \"rating\": 4,"
+ " \"reviewer\": \"Trip\","
+ " \"weight\": 5"
+ " }"
+ " ]"
+ " }"
+ " ]"
+ "}";
List output = JsonPath.read(json, "$.books[*].['book_id', 'reviews'])");
String expectedOutput =
"["
+ "{"
+ "\"book_id\":\"214515\","
+ "\"reviews\":["
+ "{"
+ "\"rating\":2,\"reviewer\":\"Amazon\",\"weight\":0"
+ "}"
+ "]"
+ "},"
+ "{"
+ "\"book_id\":\"314515\","
+ "\"reviews\":["
+ "{\"rating\":4,\"reviewer\":\"Trip\",\"weight\":5}"
+ "]"
+ "}"
+ "]";
assertEquals(expectedOutput, output.toString());
}
添加回答
举报