admin管理员组文章数量:1336411
In an Azure APIM Policy - the response can come back as either a Json Object or a Json Array - however it could be either and both scenarios need to be handled.
This will only work when the response is a Json Object:
response = context.Response.Body.As<JObject>(preserveContent: true);
But will fail for the other response which is coming in as a Json Array:
[
{
"index": 0,
"value": 999
},
{
"index": 2,
"value": 273
},
{
"index": 1,
"value": 424
}
]
Is is a generic way that both scenarios can be handled and converted to a JObject for example? Or can we check the type in a one liner ad parse accordingly?
In an Azure APIM Policy - the response can come back as either a Json Object or a Json Array - however it could be either and both scenarios need to be handled.
This will only work when the response is a Json Object:
response = context.Response.Body.As<JObject>(preserveContent: true);
But will fail for the other response which is coming in as a Json Array:
[
{
"index": 0,
"value": 999
},
{
"index": 2,
"value": 273
},
{
"index": 1,
"value": 424
}
]
Is is a generic way that both scenarios can be handled and converted to a JObject for example? Or can we check the type in a one liner ad parse accordingly?
Share asked Nov 19, 2024 at 19:07 user3437721user3437721 2,2994 gold badges36 silver badges67 bronze badges 2 |1 Answer
Reset to default 1Thanks @dbc for the comment and as started you can parse it to the base class JToken which will allow you to handle both JObject and JArray.
In order to implement this in APIM, add the below given policy to achieve this specific requirement.
<policies>
<outbound>
<base />
<set-variable name="parsedResponse" value="@(
context.Response.Body.As<JToken>(preserveContent: true) is JArray array
? new JObject(new JProperty("items", array))
: context.Response.Body.As<JObject>(preserveContent: true)
)" />
</outbound>
</policies>
You will get the below response for JObject and JArray respectively.
本文标签: jsonnetNewtonsoftJson Conversion in Azure Apim PolicyStack Overflow
版权声明:本文标题:json.net - Newtonsoft.Json Conversion in Azure Apim Policy - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742404401a2468524.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
JToken
and check the type, see JSON.NET: Why Use JToken--ever?. Or if you would prefer to deserialize to some list of POCOs you can do that with a custom converter, see How to handle both a single item and an array for the same property using JSON. Do those answer your question? Or do you need a more specific answer? – dbc Commented Nov 19, 2024 at 19:25