如何避免WSO2 ESB Foreach中介器中null值被双引号包裹
问题:WSO2 ESB Foreach中介器生成的JSON中null值被双引号包裹
在使用WSO2 ESB的Foreach中介器处理JSON数据时,生成的负载中null值会被双引号包裹成字符串"null",不符合原生JSON的格式要求。
当前代码
<enrich> <source clone="true" xpath="json-eval($.list[*])"/> <target type="body"/> </enrich> <foreach expression="json-eval($)"> <sequence> <payloadFactory media-type="json"> <format> { "Sample1": "$1", "Sample2": "$2", "Sample3": "$3", "Sample4": "$4" } </format> <args> <arg evaluator="json" expression="$.SAM1"/> <arg evaluator="json" expression="$.SAM2"/> <arg evaluator="json" expression="$.SAM3"/> <arg evaluator="json" expression="$.SAM4"/> </args> </payloadFactory> </sequence> </foreach> <enrich> <source type="body" clone="true"/> <target type="property" property="records"/> </enrich>
当前输出
{ "results": [ { "Sample1": "value", "Sample2": "value", "Sample3": "null", "Sample4": "null" } ] }
期望输出
{ "results": [ { "Sample1": "value", "Sample2": "value", "Sample3": null, "Sample4": null } ] }
解决方案
原因分析
问题出在PayloadFactory的格式定义中:所有参数都被包裹在双引号内,无论参数值是字符串还是null,都会被当作字符串进行拼接,最终null值被转换成了字符串"null"。
方法1:使用Script中介器(推荐)
用JavaScript脚本直接构建JSON对象,原生处理null值,避免字符串包裹问题:
<enrich> <source clone="true" xpath="json-eval($.list[*])"/> <target type="body"/> </enrich> <foreach expression="json-eval($)"> <sequence> <script language="js"><![CDATA[ // 获取当前Foreach迭代的JSON项 var item = mc.getPayloadJSON(); // 构建目标JSON结构 var result = { "Sample1": item.SAM1, "Sample2": item.SAM2, "Sample3": item.SAM3, "Sample4": item.SAM4 }; // 设置新的负载 mc.setPayloadJSON(result); ]]></script> </sequence> </foreach> <enrich> <source type="body" clone="true"/> <target type="property" property="records"/> </enrich>
这种方法直接操作JSON对象,原生保留null的类型,逻辑清晰且易于维护。
方法2:在PayloadFactory中使用条件判断
通过XPath的条件表达式,为非null值手动添加引号,null值则输出原生的null:
<enrich> <source clone="true" xpath="json-eval($.list[*])"/> <target type="body"/> </enrich> <foreach expression="json-eval($)"> <sequence> <payloadFactory media-type="json"> <format> { "Sample1": $1, "Sample2": $2, "Sample3": $3, "Sample4": $4 } </format> <args> <arg evaluator="json" expression="if ($.SAM1) then concat('"', $.SAM1, '"') else 'null'"/> <arg evaluator="json" expression="if ($.SAM2) then concat('"', $.SAM2, '"') else 'null'"/> <arg evaluator="json" expression="if ($.SAM3) then concat('"', $.SAM3, '"') else 'null'"/> <arg evaluator="json" expression="if ($.SAM4) then concat('"', $.SAM4, '"') else 'null'"/> </args> </payloadFactory> </sequence> </foreach> <enrich> <source type="body" clone="true"/> <target type="property" property="records"/> </enrich>
注意:这种方法需要确保表达式判断逻辑覆盖所有场景,比如空字符串等特殊情况可能需要额外处理。
内容的提问来源于stack exchange,提问作者Some Guy
相关产品推荐
相关产品推荐

