Error when deserializing JSON to Object

前端 未结 7 2097
别跟我提以往
别跟我提以往 2020-12-18 04:29

I need to convert JSON data that I get from a REST API and convert them to CSV for some analytic. The problem is that the JSON data do not necessarily follow the same conten

7条回答
  •  [愿得一人]
    2020-12-18 04:53

    The real issue here is that you are trying to deserialize into a List but your JSON actually represents a single object containing a data property which then contains a list of objects. That is why you are getting this error. Json.Net can't deserialize a single object into a list. I think what you really want to do is define a container class like this:

    class Root
    {
        public List> Data { get; set;}
    }
    

    Then deserialize like this:

    var data = JsonConvert.DeserializeObject(jsonData).Data;
    

    You will then end up with a list of dictionaries, where each dictionary represents one item in the JSON array. The dictionary key-value pairs are the dynamic values in each item. You can then work with these as you would with any other dictionary. For example, here is how you would dump out all the data:

    foreach (var dict in data)
    {
        foreach (var kvp in dict)
        {
            Console.WriteLine(kvp.Key + ": " + kvp.Value);
        }
        Console.WriteLine();
    }
    

    Fiddle: https://dotnetfiddle.net/6UaKhJ

    提交回复
    热议问题