You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过Azure API Management网关转换策略将JSON响应对象转为字符串类型?

如何用Azure API Management策略将JSON响应中的Null/Int转为字符串类型

没问题!Azure API Management(APIM)的转换策略完全能帮你实现把JSON响应里的Null、整数这类类型转成字符串的需求,我给你两种实用的方案,你可以根据自己的JSON结构来选:

方案一:用Liquid模板灵活转换

Liquid模板在APIM里处理JSON特别灵活,不管是简单结构还是嵌套复杂的JSON,都能通过它遍历处理类型转换。

举个实际例子,假设你的原始响应是这样的:

{
  "id": 123,
  "name": "Test Item",
  "description": null,
  "stock_count": 456
}

你可以在APIM的出站策略里添加set-body策略,用Liquid模板来做转换:

<outbound>
    <base />
    <set-body template="liquid">
        {
            "id": "{{body.id | to_s}}",
            "name": "{{body.name}}",
            "description": {% if body.description == null %}""{% else %}"{{body.description}}"{% endif %},
            "stock_count": "{{body.stock_count | to_s}}"
        }
    </set-body>
</outbound>
  • 小细节说明:
    • to_s过滤器会直接把整数转成字符串类型
    • 对于Null值,这里判断后输出空字符串,如果你需要输出"null"字符串,把代码里的""改成"null"就行

要是你的JSON有嵌套数组,Liquid也能轻松处理,比如:

<set-body template="liquid">
    {
        "product_list": [
            {% for product in body.product_list %}
            {
                "product_id": "{{product.id | to_s}}",
                "remark": {% if product.remark == null %}""{% else %}"{{product.remark}}"{% endif %}
            }{% unless forloop.last %},{% endunless %}
            {% endfor %}
        ]
    }
</set-body>

方案二:用json-transform做结构化转换

如果你的JSON结构是固定的,APIM内置的json-transform策略会更高效,它基于JOLT转换规则,适合规整的JSON结构。

还是用上面的示例,配置策略如下:

<outbound>
    <base />
    <json-transform>
        <context>
            <input>@(context.Response.Body.AsJObject())</input>
            <output>@(new JObject())</output>
        </context>
        <template>
            {
                "id": "=toString($.id)",
                "name": "$.name",
                "description": "=isNull($.description) ? '' : toString($.description)",
                "stock_count": "=toString($.stock_count)"
            }
        </template>
    </json-transform>
</outbound>
  • 小细节说明:
    • toString()函数专门用来把数值类型转成字符串
    • isNull()函数判断字段是否为Null,按需返回空字符串或转换后的字符串

一些实用提醒

  • 如果你的API响应是动态字段(字段不固定),Liquid的递归处理会更灵活,你可以写个递归的Liquid片段来遍历所有字段做转换
  • 测试的时候一定要在APIM的测试控制台里验证转换后的响应,确保所有需要转换的类型都处理正确
  • 对于大型JSON响应,json-transform的性能会略好一点,因为它是基于JOLT的高效转换逻辑

内容的提问来源于stack exchange,提问作者Shemeer BK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:53:16