Search code examples
c#json-deserialization

Nested Deserialization of a Very Long Object - From Json to C#


I want to deserialize the following string object (JSON String) into a C# List. Please note this is in JSON format, not with C# escape characters etc.

{
  "2020-01-01": 
  {
    "price" : 100
  },
  "2020-01-02": 
  {
    "price" : 101
  },
  "2020-01-03": 
  {
    "price" : 103
  },
  "2020-01-04": 
  {
    "price" : 104
  },
... 
}

Desired outcome will be a list of objects like:

class DataPoint 
{
   public string Date { get; set;}
   public int Price { get; set;}
}

for example the outcome should look like

{{"2020-01-01", 100},
{"2020-01-02", 101},
{"2020-01-03", 103},
{"2020-01-04", 104}}

Please note, the https://json2csharp.com/ solution is not acceptable for me, as the dates can be many, and it's impossible to write a class that covers all datapoints like suggested there.

Can you please suggest a method to deserialize the original string JSON object into the List type of C# collection?


Solution

  • Create a class like this:

    public class Price
    {
        public int price { get; set; }
    }
    

    Then deserialize your JSON into a Dictionary<string, Price> like this:

    var results = JsonConvert.DeserializeObject<Dictionary<string, Price>>(data);
    

    Once you have it in the dictionary, you can build a collection of items of your DataPoint class like this:

    var items = new List<DataPoint>();
    foreach (var item in results)
    {
        items.Add(new DataPoint {Date = item.Key, Price = item.Value.price});
    }
    

    or if you like big long LINQ expressions:

    var items = results.Select(item => new DataPoint {Date = item.Key, Price = item.Value.price}).ToList();
    

    That will give you the list you are looking for.