Json.Net Resolving Property Names Properly

前端 未结 2 437
余生分开走
余生分开走 2021-01-25 02:53

I am getting some data that looks like below JSON from an API

{
    body_html: \"

Test

\", id: \"cu1bpkz\", link_id: \"d3_3kkgis\",
相关标签:
2条回答
  • 2021-01-25 03:47

    You can try this. you can use JsonPropertyAttribute to tell Json.Net what the property's corresponding json field is.

    public class Comment
    {
        [JsonProperty("author_flair_text")]
        public string AuthorFlairText { get; set; }
    
        [JsonProperty("author_flair_css_class")]
        public string AuthorFlairCssClass { get; set; }
    
        [JsonProperty("author")]
        public string Author { get; set; }
    
        [JsonProperty("link_id")]
        public string LinkId { get; set; }
    
        [JsonProperty("id")]
        public string Id { get; set; }
    
        [JsonProperty("body_html")]
        public string BodyHtml { get; set; }
    
        [JsonProperty("url")]
        public string Url { get; set; }
    
        [JsonProperty("subreddit_id")]
        public string SubredditId { get; set; }
    
        [JsonProperty("subreddit")]
        public string Subreddit { get; set; }
    
        [JsonProperty("created_utc")]
        public long CreatedUtc { get; set; }
    
        [JsonProperty("body")]
        public string Body { get; set; }
    
        [JsonProperty("parent_id")]
        public string ParentId { get; set; }
    }
    

    Everything else has been taken care only URL is the property which I cannot find in the JSON. Please have a look else the code is ready to get copy paste and run.

    you could store an object of type JsonModel and in your model's constructor initialize it using JsonConvert.DeserializeObject<T>. Your public properties could then just call into that JsonModel instance and get the appropriate values.

    0 讨论(0)
  • 2021-01-25 03:59

    Use the JsonPropertyAttribute like so:

    [JsonProperty("author_flair_text")]
    public string AuthorFlairText { get; set; }
    

    This ensures it'll take the right name, different from the property in code.

    Edit: You can also use this tool for larger json files, it generates classes for your data: http://json2csharp.com/

    0 讨论(0)
提交回复
热议问题