0

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?

1 Answers1

1

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.

Flydog57
  • 6,851
  • 2
  • 17
  • 18
  • I tried your suggestion, and in the case we use "[]" around the object (however in the original example, it's an object with "{}" around it), I get the following error message "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Dictionary` because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. – Zoltan Halasz Nov 05 '20 at 09:58
  • 1
    @ZoltanHalasz If your json is exactly like you posted in the post, then Flydog57's answer should be 100% correct – maccettura Nov 05 '20 at 14:03
  • Proof of this being correct: https://dotnetfiddle.net/NAkvuw – maccettura Nov 05 '20 at 14:09
  • Yes, it is correct, I had few spaces or formatting issues in my code for the json object. – Zoltan Halasz Nov 06 '20 at 17:09