2016-06-18 61 views
1

我想用C#.NETJSON格式使用C#

{ 
    "attachments": [ 
     { 
      "fallback": "Required plain-text summary of the attachment.", 
      "color": "#36a64f", 
      "pretext": "Pre-text", 
      "author_name": "Myself", 
      "author_link": "http://author.link", 
      "author_icon": "http://author.icon", 
      "title": "This is my great title", 
      "title_link": "https://api.slack.com/", 
      "text": "This is the text field", 
      "image_url": "http://image.path", 
      "thumb_url": "http://image.path", 
      "footer": "News Article", 
      "footer_icon": "http://image.path", 
      "ts": 201601010000 
     } 
    ] 
} 

我創建了一個類,如下所示創建以下JSON對象:

public class Attachment 
{ 
    [JsonProperty("fallback")] 
    public string FallBack { get; set; } 
    [JsonProperty("color")] 
    public string Color { get; set; } 
    [JsonProperty("pretext")] 
    public string PreText { get; set; } 
    [JsonProperty("author_name")] 
    public string AuthorName { get; set; } 
    [JsonProperty("author_icon")] 
    public string AuthorIcon { get; set; } 
    [JsonProperty("title")] 
    public string Title { get; set; } 
    [JsonProperty("title_link")] 
    public string TitleLink { get; set; } 
    [JsonProperty("text")] 
    public string Text { get; set; } 
    [JsonProperty("image_url")] 
    public string ImageUrl { get; set; } 
    [JsonProperty("thumb_url")] 
    public string ThumbUrl { get; set; } 
    [JsonProperty("footer")] 
    public string Footer { get; set; } 
    [JsonProperty("footer_icon")] 
    public string FooterIcon { get; set; } 
    [JsonProperty("ts")] 
    public long TimeStamp { get; set; } 
    [JsonProperty("author_link")] 
    public string AuthorLink { get; set; } 
} 

,並試圖用JsonConvert.SerializeObject()在類但它只返回類的屬性是這樣的:

{ 
    "fallback": "Required plain-text summary of the attachment.", 
    "color": "#36a64f", 
    "pretext": "Pre-text", 
    "author_name": "Myself", 
    "author_link": "http://author.link", 
    "author_icon": "http://author.icon", 
    "title": "This is my great title", 
    "title_link": "https://api.slack.com/", 
    "text": "This is the text field", 
    "image_url": "http://image.path", 
    "thumb_url": "http://image.path", 
    "footer": "News Article", 
    "footer_icon": "http://image.path", 
    "ts": 201601010000 
} 

有關如何獲得「atta chments「部分在第一?我對JSON非常陌生,看起來web方法首先需要「附件」數組

+1

'public List attachments {get;組; }' –

回答

2

爲什麼不添加另一個類並對其進行序列化?

public class AttachmentsCollection 
{ 
    [JsonProperty("attachments")] 
    public Attachment[] attachments; 
} 
+1

我使用了List 而不是Attachment數組,它按預期工作。非常感謝。 –