Home > Software design >  JSON.NET Deserializing a JSON into a dictionary comes back as null
JSON.NET Deserializing a JSON into a dictionary comes back as null

Time:12-26

I have this JSON string: {"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.

CodePudding user response:

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

CodePudding user response:

you should do like this.

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

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

var obj = JsonConvert.DeserializeObject<Dictionary<string, Price>>(json);
  • Related