【问题标题】:Condition based API url in JSONJSON 中基于条件的 API url
【发布时间】:2020-05-24 22:28:40
【问题描述】:

我正在使用 JSON 来调用某些 API。我的示例 JSON 类似于:

{
  "call": [
    {
      "url": "https://URL",
      "httpMethod": "POST",
      "httpHeaders": {
        "Accept": "application/json",
        "Content-Type": "application/json"
      },
      "httpContentType": "application/json"
    }
  ]
}

我的要求是根据某些条件选择 URL。例如,如果 employeeType='Employee' 上述 JSON 中的 url 应为 https://URL1,如果 employeeType='Contractor' 则 url 应为 https://URL2

这有可能实现吗?以及如何?

【问题讨论】:

  • 不清楚你是如何处理整个情况的。你不能在生成json之前做一个if然后用正确的链接生成它吗?或者如果你已经有了json,你仍然可以在发送之前更改它。
  • 请用显示你如何创建这个 json 的代码更新问题。

标签: json api if-statement conditional-statements


【解决方案1】:

可以。您可以使用JsonConvert.SerializeObject 并写入文件。

这里是代码。

            dynamic json = JsonConvert.DeserializeObject<object>(jsson);
            int count = 0;
            foreach (dynamic item in json["call"])
            {
                if (item.employeeType=="Contractor")
                {
                    json["call"][count].url = "https://URL2";
                    string output = JsonConvert.SerializeObject(json, Formatting.Indented);
                    File.WriteAllText("YOUR JSON DATA PATH", output);
                    count++;
                }
                else if (item.employeeType == "Employee")
                {
                    json["call"][count].url = "https://URL1";
                    string output = JsonConvert.SerializeObject(json, Formatting.Indented);
                    File.WriteAllText("YOUR JSON DATA PATH", output);
                    count++;
                }
            }

这是我编辑的json 文件。

{
  "call": [
    {
      "url": "https://URL2",
      "httpMethod": "POST",
      "httpHeaders": {
        "Accept": "application/json",
        "Content-Type": "application/json"
      },
      "httpContentType": "application/json",
      "employeeType": "Contractor"//I added employeeType if you want to fetch data from here
    },
    {
      "url": "https://URL1",
      "httpMethod": "POST",
      "httpHeaders": {
        "Accept": "application/json",
        "Content-Type": "application/json"
      },
      "httpContentType": "application/json",
      "employeeType": "Employee"
    },
    {
      "url": "https://URL1",
      "httpMethod": "POST",
      "httpHeaders": {
        "Accept": "application/json",
        "Content-Type": "application/json"
      },
      "httpContentType": "application/json",
      "employeeType": "Employee"
    }
  ]
}

【讨论】:

    猜你喜欢
    • 2012-09-11
    • 2020-12-08
    • 2021-11-23
    • 2021-12-16
    • 2023-02-17
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 2012-01-02
    相关资源
    最近更新 更多