我正在尝试弄清楚如何在Azure APIM策略编辑器中正确使用XML到JSON的转换。我已经看到了几十个例子,所有的识别都是这样的:
<xml-to-json kind="direct" apply="always" consider-accept-header="false" />但是,我无法在我的策略中找到合适的位置来放置代码,使其执行我所期望的操作。以下是我的出站策略,我希望在其中使用以下内容:
<outbound>
<base />
<choose>
<when condition="@(context.Response.StatusCode < 400)">
<set-body template="liquid">
{% if body.envelope.body.GetProjectsByQueryResponse.GetProjectsByQueryResult %}"{{body.envelope.body.GetProjectsByQueryResponse.GetProjectsByQueryResult | Replace: '\r', '\r' | Replace: '\n', '\n' | Replace: '([^\\](\\\\)*)"', '$1\"'}}"{% else %} null {% endif %}
</set-body>
</when>
<otherwise>
<set-variable name="old-body" value="@(context.Response.Body.As<string>(preserveContent: true))" />
<!-- Error response as per https://github.com/Microsoft/api-guidelines/blob/master/Guidelines.md#7102-error-condition-responses -->
<set-body template="liquid">{
"error": {
"code": "{{body.envelope.body.fault.faultcode}}",
"message": "{{body.envelope.body.fault.faultstring}}"
}
}
</set-body>
<choose>
<when condition="@(string.IsNullOrEmpty(context.Response.Body.As<JObject>(preserveContent: true)["error"]["code"].ToString()) && string.IsNullOrEmpty(context.Response.Body.As<JObject>(preserveContent: true)["error"]["message"].ToString()))">
<set-body>@{
var newResponseBody = new JObject();
newResponseBody["error"] = new JObject();
newResponseBody["error"]["code"] = "InvalidErrorResponseBody";
if (string.IsNullOrEmpty((string)context.Variables["old-body"]))
{
newResponseBody["error"]["message"] = "The error response body was not a valid SOAP error response. The response body was empty.";
}
else
{
newResponseBody["error"]["message"] = "The error response body was not a valid SOAP error response. The response body was: '" + context.Variables["old-body"] + "'.";
}
return newResponseBody.ToString();
}</set-body>
</when>
</choose>
</otherwise>
</choose>
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<xml-to-json kind="direct" apply="always" consider-accept-header="false" />
</outbound>正如您所看到的,我尝试将转换行放在出站策略的末尾,但它没有完成我所期望的操作;我仍然返回了一个xml文档。
这里的任何帮助都将有助于理解如何修改我的策略以使其发挥作用。
发布于 2021-09-28 07:03:35
为了将XML转换为JSON,您应该使用出站策略。它应该放在里面
<outbound policy>如下所示:
<policies>
<inbound>
<base />
</inbound>
<outbound>
<base />
<xml-to-json kind="direct" apply="always" consider-accept-header="false" />
</outbound>要创建它,请将光标放在outbound部分,然后单击Convert XML To JSON链接。

有关更多信息,您可以参考此link。
要了解APIM中的策略配置,请参考此link。
要获得JSON转换,只需在request headers框中添加accept: application/json即可。

如果您检查结果,则结果已转换为JSON。

https://stackoverflow.com/questions/69353330
复制相似问题