I'm having an issue while getting some JSON to deserialize. It's coming in via HttpClient from CoinGecko API.
This is the URL: GetSimplePrice
It returns:
{
"bitcoin": {
"usd": 28352.7,
"eur": 26185.8
},
"ethereum": {
"usd": 1821.4,
"eur": 1682.2
}
}
Special-Pasting the above as JSON into C# creates these classes (works):
public class Rootobject
{
public Bitcoin bitcoin { get; set; }
public Ethereum ethereum { get; set; }
}
public class Bitcoin
{
public float usd { get; set; }
public float eur { get; set; }
}
public class Ethereum
{
public float usd { get; set; }
public float eur { get; set; }
}
However, the name of the coin and the currency are dynamic fields so I can't use that exactly as is.
I've tried the below and while the deserialization works, my class returns empty:
public class SimplePrice
{
public Coin Coin { get; set; }
}
public class Coin
{
public float Price { get; set; }
}
I've been banging my head against a wall for a while on this one.
Any help would be greatly appreciated! Thanks!
From the JSON, you should deserialize as Dictionary<string, Dictionary<string, float>>
type.
Dictionary<string, Dictionary<string, float>> simplePrice = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, float>>>(json);
foreach (KeyValuePair<string, Dictionary<string, float>> coin in simplePrice)
{
Console.WriteLine($"Coin: {coin.Key}");
foreach (KeyValuePair<string, float> price in coin.Value)
{
Console.WriteLine($"{price.Key}: {price.Value}");
}
}