无需迭代即可在 Jackson 中过滤 JsonNode 数组
Filter JsonNode Array in Jackson without Iterating
Json:
{
"type":"book",
"children":[
{
"key":"123",
"name":"book1"
},
{
"key":"456",
"name":"book2"
]
}
]
}
我只想在 key = "456" 时获取书名作为字符串。
这是我的:
JsonNode root = mapper.readTree(investigation.getFilterModel());
JsonNode children = root.path("children");
if (children.isArray())
{
for (final JsonNode objNode : children)
{
if ("456".equalsIgnoreCase(objNode.path("key").textValue()))
{
String bookName = objNode.path("name").textValue();
}
}
}
这对我有用。我只想知道是否有一种更简洁的方法可以在不遍历整个子数组的情况下做到这一点?由于数组的大小可以很大。
Jackson 无法进行此类查询。当您知道元素所在的数组索引时,最多可以使用 JsonPointer
表达式:
root.at("/children/1/name");
您可以使用 Jayway JsonPath 库支持的 JsonPath 表达式 $.children[?(@.key==456)].name
进行查询。
Json:
{
"type":"book",
"children":[
{
"key":"123",
"name":"book1"
},
{
"key":"456",
"name":"book2"
]
}
]
}
我只想在 key = "456" 时获取书名作为字符串。
这是我的:
JsonNode root = mapper.readTree(investigation.getFilterModel());
JsonNode children = root.path("children");
if (children.isArray())
{
for (final JsonNode objNode : children)
{
if ("456".equalsIgnoreCase(objNode.path("key").textValue()))
{
String bookName = objNode.path("name").textValue();
}
}
}
这对我有用。我只想知道是否有一种更简洁的方法可以在不遍历整个子数组的情况下做到这一点?由于数组的大小可以很大。
Jackson 无法进行此类查询。当您知道元素所在的数组索引时,最多可以使用 JsonPointer
表达式:
root.at("/children/1/name");
您可以使用 Jayway JsonPath 库支持的 JsonPath 表达式 $.children[?(@.key==456)].name
进行查询。