[英]Finding value in Jackson JsonNode without serialization
I have multiple complex (Jackson) JsonNode structures which I need to find a value in. The problem is very similar to: how to parse json array value using json node and Jackson JsonNode Serialization .我有多个复杂的(杰克逊)JsonNode 结构,我需要在其中找到一个值。问题非常类似于: 如何使用 json 节点和Z7930C951E609E461E8226004ED91A8解析 json 数组值
So I would like to find a value inside a JsonNode with the following limitation: The context is provided by (Cucumber) tests.所以我想在 JsonNode 中找到一个具有以下限制的值:上下文由(Cucumber)测试提供。 eg 'Inside "title/configurations/relation" I see the value "a" ' see example below.例如,“在“标题/配置/关系”中,我看到了值“a”,请参见下面的示例。
The code I've tried to use:我尝试使用的代码:
public JsonNode findNodeInPath (String path, JsonNode parent) {
int firstSlash = path.indexOf("/");
if (parent == null) {
return null;
}
else {
String nextNodeName = firstSlash == -1 ? path : path.substring(0, firstSlash);
if (parent.isObject()) {
return findNodeInPath(firstSlash == -1 ? path : path.substring(firstSlash + 1), parent.findValue(nextNodeName));
}
else { // parent is array
if (parent.has(path)) {
return parent;
}
for (JsonNode node : parent) {
JsonNode nextNode = node.findValue(nextNodeName);
if (nextNode != null) {
return findNodeInPath(firstSlash == -1 ? path : path.substring(firstSlash + 1), nextNode);
}
}
}
return null; // not found
}
}
But that doesn't work because when I get to a JsonArray with strings only (like "relation" below) Jackson doesn't let me access the text inside it.但这不起作用,因为当我到达一个仅包含字符串的 JsonArray 时(如下面的“关系”),Jackson 不允许我访问其中的文本。
I don't want to create a POJO for each JsonNode because:我不想为每个 JsonNode 创建一个 POJO,因为:
The variance between nodes is very big.节点之间的差异非常大。 I can't see any object that will fit even most of the configurations I have.我看不到任何适合我拥有的大多数配置的 object。
This is used for testing only.这仅用于测试。 The structures as they are, just sit on the database.它们的结构,只是放在数据库上。 I wouldn't like to create objects solely for testing purposes.我不想仅仅为了测试目的而创建对象。
An example of a JsonNode I have:我有一个 JsonNode 的例子:
{
"title": [
{
"configuration": [
{
"product1": {
"id": "id1",
"name": [
{
"locale": "en_US",
"value": "value1"
}
]
},
"configured": true,
"relation": ["a","b","c"],
"relation2": []
}
]
}
]
}
I apologize for the long question, any help (from any direction) would be greatly appreciated.对于这个冗长的问题,我深表歉意,任何帮助(来自任何方向)将不胜感激。
Extract Array node:提取数组节点:
JsonNode node = jsonNode.findPath("relation");
Convert the array node to List of strings:将数组节点转换为字符串列表:
List<String> relationList = new ObjectMapper().readValue(node.toString(), new TypeReference<List<String>>() {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.