我有如下所示的json表示形式:
{
"total": "555",
"offset": "555",
"hasMore": "false",
"results": [
{
"associations": {
"workflowIds": [],
"companyIds": [],
"ownerIds": [],
"child": {
"name" : "association1",
"key" : "a1"
},
"quoteIds": [],
"contentIds": [],
"dealIds": [],
"contactIds": [
4646915
],
"ticketIds": []
},
"scheduledTasks": [
{
"taskType": "REMINDER",
"portalId": 214129,
"engagementType": "TASK",
"engagementId": 6604524566,
"timestamp": 1586815200000
}
]
},
{
"associations": {
"workflowIds": [],
"companyIds": [],
"ownerIds": [],
"quoteIds": [],
"contentIds": [],
"child": {
"name" : "association2",
"key" : "a2"
},
"dealIds": [],
"contactIds": [
4646915
],
"ticketIds": []
}
},
{
"associations": {
"workflowIds": [],
"companyIds": [],
"ownerIds": [],
"quoteIds": [],
"contentIds": [],
"dealIds": [],
"child": {
"name" : "association3",
"key" : "a3"
},
"contactIds": [
3995065
],
"ticketIds": []
}
},
{
"associations": {
"workflowIds": [],
"companyIds": [],
"ownerIds": [],
"quoteIds": [],
"contentIds": [],
"dealIds": [],
"contactIds": [
4648365
],
"ticketIds": []
}
}
]
}
我想通过传递节点选择器字符串来获取给定节点的过滤信息(类似于sql),要实现这一点,我正在执行以下操作:
ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(new File("/Users/pra/automation/foo.json"));
String result = root.at("/results/0/associations/0/child").toString();
Assert.assertNotNull(result);
并且此代码也正常工作,因为传递了0级索引,所以它从数组中筛选出了第一个节点,但是我需要输出所有匹配的元素,以实现我传递了*而不是0,但它不起作用。
意味着我正在尝试类似以下操作(失败):
String result = root.at("/results/*/associations/*/child").toString();
所需的所需输出:
[
{
"name" : "association1",
"key" : "a1"
},
{
"name" : "association2",
"key" : "a2"
},
{
"name" : "association3",
"key" : "a3"
}
]
我愿意接受其他基于Java的替代方案来实现这一目标。谢谢。
如果您可以切换到Gson库,则可以使用im.wilk.vor:Voritem库gitHub或在Maven存储库中。
VorItem vorItemFactory = VorItemFactoryBuilder.standard.build();
JsonElement je = JsonParser.parse(...)
VorItem vi = vorItemFactory.from(je);
VorItem result = vorItemFactory.empty();
for (int idx = 0; idx < vi.get("result").list().size(); idx++) {
result.get(idx).set("name", vi.get("result").get(idx).get("associations/child/name");
result.get(idx).set("key", vi.get("result").get(idx).get("associations/child/key");
}
return result.asJsonElement().toString();