首页 > 解决方案 > 如何将 Azure APIM 连接到逻辑应用以转换 API 响应的 JSON 结构?

问题描述

我已经阅读并关注了多个帖子,但我无法解决我的问题:

我已经创建了一个 APIM(Azure API 管理)服务,并且该服务有效,网关 URL www.azurebroker.nl/azurebroker/factuur(例如)向我自己的 API(www.ownapi.nl/invoice)发出请求。该 API 的响应如下:

{
"invoiceID":1,
"formType":"invoice",
"amount":449,
"currency":"eur",
"description":"Invoice real estate",
"period":{"end":20122019,"start":20122020},
"owner"{"id":91434,"firstname":"User","lastname":"UserName","dateOfBirth":1121993,"phoneNumber":3487378434,"countryOfBirth":"Nederland","IBAN":"NL28 ABNA 743734763474324"},
"property":{"id":105,"type":"apartment","address":"ghost lane 13","ZIP":"7888 CK","State\/Province":"Groningen","country":"Nederland","construction-year":15072009,"previousOwners":9},
"previousProperties":[54,193,11,454,18]
}

现在我正在尝试将上述响应的结构转换为不同的结构,例如:

{
"general": {
"invoiceID": 12,
"formType": "invoice",
"amount": 449,
"currency": "eur",
"description": "Invoice real estate",
"period": {
  "end": 20122019,
  "start": 20122020
}
},
"owner": {
"id": 91434,
"name": "User, Username",
"dateOfBirth": 1121993,
"phoneNumber": 646068151,
"countryOfBirth": "Nederland",
"IBAN": "NL28 ABNA 743734763474324"
},
"property": {
  "id": 105,
  "type": "apartment",
  "fullAddress": "ghost lane 13, 7888 CK Groningen Nederland",
  "construction-year": 15072009,
  "previousOwners": 9
},
"previousProperties": [ 54, 193, 11, 454, 18 ]
}

仔细观察,一些字段发生了变化,例如:

名字 + 姓氏现在是名字。invoiceID、formType、金额、货币、描述现在放在名为“general”的对象中。

我尝试在逻辑应用中执行以下操作:

在此处输入图像描述

该动作的请求体schema输入字段是本文提到的第一个JSON的schema。在此操作之后,我尝试了“解析 JSON”操作:

在此处输入图像描述

在“Parse Json”操作的 Schema 输入字段中,我填充了本文中提到的第二个 JSON 的 JSON 模式。

希望我的目标对你们来说很清楚,有人可以帮助我。我正在尝试使用我的 API 管理网关 URL 映射我的请求响应的 json 结构。

提前致谢

标签: azureapiazure-logic-appsazure-api-management

解决方案


如果要使用 LA,可以使用send-requestAPIM 中的策略来编写新的 HTTP 请求并调用 LA,然后使用set-body来自 LA 的响应覆盖响应正文。但是,如果您只需要这种 JSON 转换,您可以避免使用 LA 并在 APIM 中完成所有操作。在您的操作策略的内部outbound部分添加:

<set-body>@{
    var body = context.Response.Body.As<JObject>();

    var newBody = new JObject(new JProperty("general", body));

    var owner = (JObject)body["owner"];
    owner["name"] = $"{owner["firstname"]}, {owner["lastname"]}";
    owner.Remove("firstname");
    owner.Remove("lastname");
    body.Remove("owner");
    newBody.Add("owner", owner);

    var property = (JObject)body["property"];
    property["fullAddress"] = $"{property["address"]}, {property["ZIP"]} {property["State/Province"]} {property["country"]}";
    property.Remove("address");
    property.Remove("ZIP");
    property.Remove("State/Province");
    property.Remove("country");
    body.Remove("property");
    newBody.Add("property", property);

    var previousProperties = (JArray)body["previousProperties"];
    body.Remove("previousProperties");
    newBody.Add("previousProperties", previousProperties);

    return newBody.ToString();
}</set-body>

根据您的确切转换,您可能更喜欢挑选所有属性,甚至使用液体模板来构造主体,set-body策略支持.


推荐阅读