我的要求是解析大量后端响应,可以是 json 或 xml。我现在不知道他们的 react 结构。所以,我必须以这样的方式编写一个java工具,我的工具应该能够根据配置文件解析响应,该配置文件将由服务团队在运行我的工具之前进行配置,因为他们将到达知道这些值,他们必须通过我的工具检索。例如,如果后端 json 或 xml 响应如下所示,并且我的配置为 Employee.details.referenced[0].type,则通过工具检索到的值应为“customer-support”。我将无法使用 pojo 或其他与后端响应耦合的东西,因为我不知道后端响应,并且我的同一工具应该适用于不同的后端,这些后端以不同的结构输出响应:
Json:
{
"Employee": [
{
"id": "12345678",
"service": "ps",
"origin": {
"address": {
"addressLocality": "India"
}
},
"destination": {
"address": {
"addressLocality": "US"
}
},
"status": {
"timestamp": "2019-01-29T21:02:49Z",
"location": {
"address": {
"addressLocality": "Germany"
}
},
"Code": "xyz",
"description": "Services"
},
"details": {
"references": [
{
"number": "0003030891",
"type": "customer-support"
}
]
}
}
]
}
XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Employee>
<element>
<destination>
<address>
<addressLocality>US</addressLocality>
</address>
</destination>
<details>
<references>
<element>
<number>0003030891</number>
<type>customer-support</type>
</element>
</references>
</details>
<id>12345678</id>
<origin>
<address>
<addressLocality>India</addressLocality>
</address>
</origin>
<service>ps</service>
<status>
<Code>xyz</Code>
<description>Services</description>
<location>
<address>
<addressLocality>Germany</addressLocality>
</address>
</location>
<timestamp>2019-01-29T21:02:49Z</timestamp>
</status>
</element>
</Employee>
</root>
我尝试检查 java 中的 json 解析器和 xml saxparser。但是,似乎所有人都必须提前知道后端响应。
最佳答案
另一位发帖者已经指出了Jackson图书馆,但我想添加我的想法:
Jackson 能够将String
(或任何其他几个 I/O 源)直接解析为 JsonNode
:
String json = backEndProvider.fetch(); // example call
JsonNode node = new ObjectMapper().readTree(json);
然后,您可以使用其 .get()
访问生成的 JsonNode
的子节点。方法:
JsonNode child = node.get("childKey");
此外,可以使用多种转换方法来访问最终值。例如,如果您知道 child
是文本,则可以通过以下方式获取 child
的值:
String childValue = child.asText();
另请参阅this Baeldung article .
从这里,您可以将用户的输入字符串(例如 Employee.details.referenced[0].type
)解析为键数组(例如 ["Employee", "details ", "referenced[0]", "type"]
) 并递归访问根元素,直到获取足够的值,并在每个阶段检查键是否是数组访问操作。如果您没有任何类型信息,则需要从引用解析器返回 JsonNode
或 Object
。
对于数组访问,例如 referenced[0]
,请注意 ArrayNode
继承 ObjectNode
和 its get()
method is overriden to use an int
.
请注意,上面的解决方案与 Jackson 的 XmlMapper
的工作原理相同。 .
关于java - 使用 java 使用给定的键解析复杂的 json 和 xml,无需使用 pojo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56250609/