最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

json.net - Newtonsoft.Json Conversion in Azure Apim Policy - Stack Overflow

programmeradmin20浏览0评论

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 You could parse to the base class 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
  • I think checking the type could work if you want to put that as the answer I can accept it – user3437721 Commented Nov 19, 2024 at 20:15
Add a comment  | 

1 Answer 1

Reset to default 1

Thanks @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(&quot;items&quot;, array)) 
            : context.Response.Body.As<JObject>(preserveContent: true)
        )" />
    </outbound>
</policies>

You will get the below response for JObject and JArray respectively.

发布评论

评论列表(0)

  1. 暂无评论