首页 > 解决方案 > 在 C# REST-Client 中规避 API 响应规范违规的最简单方法

问题描述

我目前的任务是实现一个与Magento 2 的 REST-API通信的工具

Magento2 提供了一个Swagger 2.0 JSON 模式,它允许我(在修复了模式中的许多问题之后)使用 NSwag 生成一个合适的客户端。

现在的问题是:Magento 2 REST API在某些时候没有遵循自己的规范。

我已经通过手动修复生成的代码解决了一些问题。但是,由于规范在类型方面与现实不符,我不断遇到新问题。

例如,模式指定:

"framework-attribute-interface": {
    "type": "object",
    "description": "Interface for custom attribute value.",
    "properties": {
        "attribute_code": {
            "type": "string",
            "description": "Attribute code"
        },
        "value": {
            "type": "string",
            "description": "Attribute value"
        }
    },
    "required": ["attribute_code", "value"]
}

但是,实际的 API 可能会返回 astring或 an array,如以下响应示例片段所示:

{
    "attribute_code": "category_ids",
    "value": ["6", "8", "16"]
}, {
    "attribute_code": "required_options",
    "value": "0"
}

虽然我可以花几天时间测试整个 API 并修复所有问题,但出于明显的原因(时间),我想避免这种情况。因此,现在的问题是是否有一些简单、懒惰的方式来“自动转换”所有内容(想避免dynamic顺便说一句)?

使用的 JSON 框架是Newtonsoft.Json. 通讯工作通过.NET Framework System.Net.Http.HttpClient

标签: c#jsonrestmagentomagento2

解决方案


推荐阅读