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.
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