嵌套属性的C#模型

时间:2018-01-12 14:14:43

标签: c# .net asp.net-core

我需要向CloudFlare发出API请求以清除单个文件的缓存。

有人可以指导如何将下面的内容表示为C#模型类。

files: [
        "http://www.example.com/css/styles.css",
        {
          "url": "http://www.example.com/cat_picture.jpg",
          "headers": {
            "Origin": "cloudflare.com",
            "CF-IPCountry": "US",
            "CF-Device-Type": "desktop"
          }
        }
      ]

2 个答案:

答案 0 :(得分:3)

    var obj = new
    {
        files = new object[]
        {
            "http://www.example.com/css/styles.css",
            new
            {
                url = "http://www.example.com/cat_picture.jpg",
                headers = new Dictionary<string,string>
                {
                    { "Origin", "cloudflare.com" },
                    { "CF-IPCountry","US" },
                    { "CF-Device-Type", "desktop"}
                }
            }
        }
    };

字典就在那里,因为像CF-IPCountry这样的尴尬属性名称使得无法使用匿名类型。

显示它的工作原理:

var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Formatting.Indented);

给出:

{
  "files": [
    "http://www.example.com/css/styles.css",
    {
      "url": "http://www.example.com/cat_picture.jpg",
      "headers": {
        "Origin": "cloudflare.com",
        "CF-IPCountry": "US",
        "CF-Device-Type": "desktop"
      }
    }
  ]
}

编辑;这不太对 - 字典不起作用,但我没时间修复它。

答案 1 :(得分:1)

使用类(也许你可以使用更好的类名,然后我的:)):

class Root
{
    [JsonProperty(PropertyName = "files")]
    public List<object> Files { get; set; } = new List<object>();
}

class UrlContainer
{
    [JsonProperty(PropertyName = "url")]
    public string Url { get; set; }

    [JsonProperty(PropertyName = "headers")]
    public Headers Headers { get; set; }
}

class Headers
{
    public string Origin { get; set; }

    [JsonProperty(PropertyName = "CF-IPCountry")]
    public string CfIpCountry { get; set; }

    [JsonProperty(PropertyName = "CF-Device-Type")]
    public string CfDeviceType { get; set; }
}

<强>用法

var root = new Root();

// Add a simple url string
root.Files.Add("http://www.example.com/css/styles.css");

var urlContainer = new UrlContainer() {
    Url = "http://www.example.com/cat_picture.jpg",
    Headers = new Headers()
    {
        Origin = "cloudflare.com",
        CfIpCountry = "US",
        CfDeviceType = "desktop"
    }
};

// Adding url with headers
root.Files.Add(urlContainer);

string json = JsonConvert.SerializeObject(root);

注意:我正在使用Newtonsoft.Json