Deserializing JSON data to C# using JSON.NET

前端 未结 7 1714
离开以前
离开以前 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:38

    You can try checking some of the class generators online for further information. However, I believe some of the answers have been useful. Here's my approach that may be useful.

    The following code was made with a dynamic method in mind.

    dynObj = (JArray) JsonConvert.DeserializeObject(nvm);
    
    foreach(JObject item in dynObj) {
     foreach(JObject trend in item["trends"]) {
      Console.WriteLine("{0}-{1}-{2}", trend["query"], trend["name"], trend["url"]);
     }
    }
    

    This code basically allows you to access members contained in the Json string. Just a different way without the need of the classes. query, trend and url are the objects contained in the Json string.

    You can also use this website. Don't trust the classes a 100% but you get the idea.

    0 讨论(0)
  • 2020-11-22 04:45

    Assuming your sample data is correct, your givenname, and other entries wrapped in brackets are arrays in JS... you'll want to use List for those data types. and List for say accountstatusexpmaxdate... I think you example has the dates incorrectly formatted though, so uncertain as to what else is incorrect in your example.

    This is an old post, but wanted to make note of the issues.

    0 讨论(0)
  • 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<T>
        {
            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<T>(response.Content.ReadAsStringAsync().Result, settings);
                    }
                }
                return result;
            }
        }
    }
    

    Usage would be like:

    ApiConsumer<FeedResult> feed = new ApiConsumer<FeedResult>("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

    0 讨论(0)
  • 2020-11-22 04:52

    Have you tried using the generic DeserializeObject method?

    JsonConvert.DeserializeObject<MyAccount>(myjsondata);
    

    Any missing fields in the JSON data should simply be left NULL.

    UPDATE:

    If the JSON string is an array, try this:

    var jarray = JsonConvert.DeserializeObject<List<MyAccount>>(myjsondata);
    

    jarray should then be a List<MyAccount>.

    ANOTHER UPDATE:

    The exception you're getting isn't consistent with an array of objects- I think the serializer is having problems with your Dictionary-typed accountstatusmodifiedby property.

    Try excluding the accountstatusmodifiedby property from the serialization and see if that helps. If it does, you may need to represent that property differently.

    Documentation: Serializing and Deserializing JSON with Json.NET

    0 讨论(0)
  • 2020-11-22 04:53

    You can use:

    JsonConvert.PopulateObject(json, obj);
    

    here: json is the json string,obj is the target object. See: example

    Note: PopulateObject() will not erase obj's list data, after Populate(), obj's list member will contains its original data and data from json string

    0 讨论(0)
  • 2020-11-22 04:54

    I found my I had built my object incorrectly. I used http://json2csharp.com/ to generate me my object class from the JSON. Once I had the correct Oject I was able to cast without issue. Norbit, Noob mistake. Thought I'd add it in case you have the same issue.

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