WSO2,XML 到 JSON,强制将单个元素视为数组 [英] WSO2, XML to JSON, force a single element to be treated as array
问题描述
在 Enterprise Integrator 6.6.0 中,我将 XML 转换为 JSON 有效负载.
In Enterprise Integrator 6.6.0 I'm converting a XML to JSON payload.
如果 XML 源只有一个元素,它显然会被视为单个对象
If the XML source has a single element it gets obviously treated as a single object
<items>
<item></item>
</items>
变成
{
"items": {
"item": {}
}
}
但如果有更多元素,则将特定对象视为数组
but if there are more element, the specific object is treated as an array
<items>
<item></item>
<item></item>
</items>
变成
{
"items": {
"item": [{}, {}]
}
}
有没有办法对齐特定子对象的转换?在这种情况下,我试图始终返回一个 item 数组,即使只有一个元素.
Is there a way to align the conversion of a specific sub-object? In this case, I'm trying to always return an item array, even when there is only a single element.
我了解了 xml-multiple
属性,但我不明白如何使用它;是否要手动设置为源 xml 负载?
I read about the xml-multiple
property but I couldn't understand how to use it; is it to be set manually to the source xml payload?
推荐答案
您可以使用 Json 转换介体[1] 来实现您的用例.这里我们需要定义 json 模式以匹配预期的数据结构.对于上述情况,您将能够使用类似于以下内容的 json 模式.
You can use the Json transform mediator[1] to achieve your use-case. Here we need to define the json schema to match the expected data structure. For the above case you will be able to use a json schema similar to the following.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"items": {
"type": "object",
"properties": {
"item": {
"type": "array",
"items": [
{
"type": "object"
}
]
}
},
"required": [
"item"
]
}
},
"required": [
"items"
]
}
这指定项目是一个数组.然后可以将模式添加到注册表 [2] 并在 json 转换介体中引用.Json 转换中介器需要在 xml 到 json 转换之后添加.请参阅以下示例代理服务.
This specifies that the item is an array. Then the schema can be added to the registry [2] and referred in the json transform mediator. The Json transform mediator needs to be added after the xml to json transformation. Refer to the following sample proxy service.
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="transform"
startOnLoad="true"
statistics="disable"
trace="disable"
transports="http,https">
<target>
<inSequence>
<property name="messageType" scope="axis2" value="application/json"/>
<property name="ContentType" scope="axis2" value="application/json"/>
<jsontransform schema="conf:/schema.json"/>
<respond/>
</inSequence>
</target>
<description/>
</proxy>
输入 1
<items>
<item><val1></val1></item>
<item><val1></val1></item>
</items>
输出 1
{
"items": {
"item": [
{
"val1": null
},
{
"val1": null
}
]
}
}
输入 2
<items>
<item><val1></val1></item>
</items>
输出 2
{
"items": {
"item": [
{
"val1": null
}
]
}
}
[1]-https://docs.wso2.com/display/EI660/JSON+Transform+Mediator
[1]-https://docs.wso2.com/display/EI660/JSON+Transform+Mediator
[2]-https://docs.wso2.com/display/EI660/Managing+the+Registry+
[2]-https://docs.wso2.com/display/EI660/Managing+the+Registry+
这篇关于WSO2,XML 到 JSON,强制将单个元素视为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!