【问题标题】:C# model for nested properties嵌套属性的 C# 模型
【发布时间】:2018-01-12 14:14:42
【问题描述】:

我需要向 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"
          }
        }
      ]

【问题讨论】:

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


【解决方案1】:
    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"
      }
    }
  ]
}

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

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      相关资源
      最近更新 更多