Search code examples
c#jsonjson.netdeserialization

JSON.NET Deserializing a JSON into a dictionary comes back as null


I have this JSON:

{
  "AAPL": { "price": "131.85000" },
  "eur/usd": { "price": "1.06290" },
  "msft": { "price": "238.76000" }
}

When I try to deserialize this into a dictionary it comes back as null.

I am using the TwelveDataAPI. https://twelvedata.com/docs#real-time-price

I have tried creating a simple class that will allow me to deserialize this JSON even if there are different tickers and different amounts of them.

My class:

public class CurrentPriceClass
{
    public class Root
    {
        public Dictionary<string, Price> Prices { get; set; }
    }

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

But when I try to deserialize it, it comes back as null, and I cannot iterate over it:

CurrentPriceClass.Root priceRoot = JsonConvert.DeserializeObject<CurrentPriceClass.Root>(
dataJson);
foreach (KeyValuePair<string, CurrentPriceClass.Price> price in priceRoot.Prices)
{
    Console.WriteLine($"{price.Key}: {price.Value.price}");
}

The error I get when iterating is:

Object reference not set to an instance of an object.

When debugging priceRoot is null. I am assuming that this is a problem with my class.


Solution

  • Deserialize as Dictionary<string, CurrentPriceClass.Price> without needing the root class (CurrentPriceClass).

    Dictionary<string, CurrentPriceClass.Price> priceRoot = JsonConvert.DeserializeObject<Dictionary<string, CurrentPriceClass.Price>>(dataJson);
    
    foreach (KeyValuePair<string, CurrentPriceClass.Price> price in priceRoot)
    {
        Console.WriteLine($"{price.Key}: {price.Value.price}");
    }
    

    Demo @ .NET Fiddle