如何在WSO2 ESB代理服务中解析JSON动态数组并转换为XML
嘿,我来帮你搞定这个转换需求!WSO2 ESB里处理动态数组的JSON转XML,主要有两种常用方式,我给你详细拆解一下:
方法一:PayloadFactory + Foreach 中介器(适合简单场景)
首先,WSO2 ESB默认会把收到的JSON转换成特定结构的XML,所以我们第一步先把JSON转成XML,再通过遍历数组来构建目标格式。
完整代理服务配置示例
<proxy xmlns="http://ws.apache.org/ns/synapse" name="GoogleBooksProxy" transports="http https" startOnLoad="true"> <target> <inSequence> <!-- 发送请求到Google Books API --> <send> <endpoint> <address uri="https://www.googleapis.com/books/v1/volumes?q=web+services"/> </endpoint> </send> </inSequence> <outSequence> <!-- 1. 将JSON响应转换为WSO2内部XML结构 --> <json-to-xml/> <!-- 2. 初始化存储author元素的属性 --> <property name="authorElements" value="" scope="default"/> <!-- 3. 提取书籍标题 --> <property name="bookTitle" expression="//jsonObject/items/jsonObject/volumeInfo/title/text()" scope="default"/> <!-- 4. 遍历authors数组,逐个构建<author>元素 --> <foreach expression="//jsonObject/items/jsonObject/volumeInfo/authors/jsonPrimitive" id="authorsLoop"> <sequence> <property name="currentAuthor" expression="text()" scope="default"/> <!-- 拼接author元素字符串 --> <property name="authorElements" expression="fn:concat($ctx:authorElements, '<author>', $ctx:currentAuthor, '</author>')" scope="default"/> </sequence> </foreach> <!-- 5. 用PayloadFactory组装最终XML格式 --> <payloadFactory media-type="xml"> <format> <items> <title>$1</title> <authors>$2</authors> </items> </format> <args> <arg evaluator="xml" expression="$ctx:bookTitle"/> <arg evaluator="xml" expression="$ctx:authorElements"/> </args> </payloadFactory> <!-- 6. 将响应发送给客户端 --> <send/> </outSequence> <faultSequence> <log level="full"/> <send/> </faultSequence> </target> </proxy>
关键步骤说明
<json-to-xml/>:把Google Books返回的JSON转换成WSO2的内部XML结构,方便后续XPath处理foreach中介器:遍历authors数组下的每个作者节点,逐个拼接成<author>元素字符串PayloadFactory:把提取的标题和拼接好的作者元素组合成你需要的目标XML格式
方法二:XSLT 中介器(更灵活的复杂转换)
如果后续有更复杂的转换需求,XSLT会是更合适的选择,它天生擅长处理动态XML结构。
第一步:编写XSLT转换文件
创建一个名为transformBooks.xsl的文件,内容如下:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <!-- 匹配JSON转XML后的根节点 --> <xsl:template match="/jsonObject"> <items> <!-- 提取标题 --> <title> <xsl:value-of select="items/jsonObject/volumeInfo/title"/> </title> <!-- 遍历authors数组生成<author>元素 --> <authors> <xsl:for-each select="items/jsonObject/volumeInfo/authors/jsonPrimitive"> <author> <xsl:value-of select="."/> </author> </xsl:for-each> </authors> </items> </xsl:template> </xsl:stylesheet>
第二步:在WSO2 ESB中配置代理服务
把上面的XSLT文件上传到WSO2 ESB的注册表(比如conf:/transformBooks.xsl),然后修改代理服务的outSequence:
<outSequence> <!-- 1. 将JSON转换为XML --> <json-to-xml/> <!-- 2. 应用XSLT转换 --> <xslt key="conf:/transformBooks.xsl"/> <!-- 3. 发送响应给客户端 --> <send/> </outSequence>
优势说明
- XSLT的方式更清晰,逻辑集中在样式表中,便于维护和扩展
- 如果后续需要处理更多字段(比如publisher、publishedDate),直接修改XSLT即可,不需要调整中介器序列
注意事项
- 如果Google Books API返回的
items数组包含多个书籍,你需要在外层再加一个foreach遍历items下的每个jsonObject节点,生成多个<items>元素 - 测试时可以用
<log level="full"/>查看每一步的消息结构,方便排查问题
内容的提问来源于stack exchange,提问作者Sid
相关产品推荐
相关产品推荐

