Deserializing JSON data to C# using JSON.NET

前端 未结 7 1713
离开以前
离开以前 2020-11-22 04:01

I\'m relatively new to working with C# and JSON data and am seeking guidance. I\'m using C# 3.0, with .NET3.5SP1, and JSON.NET 3.5r6.

I have a defined C# class that

7条回答
  •  情歌与酒
    2020-11-22 04:46

    Building off of bbant's answer, this is my complete solution for deserializing JSON from a remote URL.

    using Newtonsoft.Json;
    using System.Net.Http;
    
    namespace Base
    {
        public class ApiConsumer
        {
            public T data;
            private string url;
    
            public CalendarApiConsumer(string url)
            {
                this.url = url;
                this.data = getItems();
            }
    
            private T getItems()
            {
                T result = default(T);
                HttpClient client = new HttpClient();
    
                // This allows for debugging possible JSON issues
                var settings = new JsonSerializerSettings
                {
                    Error = (sender, args) =>
                    {
                        if (System.Diagnostics.Debugger.IsAttached)
                        {
                            System.Diagnostics.Debugger.Break();
                        }
                    }
                };
    
                using (HttpResponseMessage response = client.GetAsync(this.url).Result)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        result = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result, settings);
                    }
                }
                return result;
            }
        }
    }
    

    Usage would be like:

    ApiConsumer feed = new ApiConsumer("http://example.info/feeds/feeds.aspx?alt=json-in-script");
    

    Where FeedResult is the class generated using the Xamasoft JSON Class Generator

    Here is a screenshot of the settings I used, allowing for weird property names which the web version could not account for.

    Xamasoft JSON Class Generator

提交回复
热议问题