给出JSON对象,例如:
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"book_id": "214515",
"title": "Sayings of the Century",
"price": 8.95,
"reviews": [
{
"rating": 2,
"reviewer": "Amazon",
"weight": 0
},
{
...
}
]
},
{
...
}
是否有可能选择book_id以及该书的部分或全部评论?
结果可能看起来像这样:
[
{
"book_id": "...",
"reviews": [
...
]
},
{
...
}
]
我一直在使用Jayway jsonpath:https://github.com/json-path/JsonPath
在处理数组(例如“评论”)然后以编程方式加入时,以下不适合作为解决方案:
List ids = JsonPath.read(json, "$.store.books[*].book_id");
List reviews = JsonPath.read(json, "$.store.books[*].reviews[*]");
答案 0 :(得分:1)
在文档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());
}