I have an issue with deserializing the JSON file from the web to a List
.
My code is down below, but it does not execute and shows Newtonsoft.Json.JsonSerializationException
.
static void Main(string[] args)
{
List<Root> coinDatas = new List<Root>(); ;
callApi(coinDatas);
Console.ReadKey();
}
private static async void callApi(List<Root> coinDatas)
{
string url = "https://api.coinstats.app/public/v1/coins?skip=0&limit=50¤cy=USD";
HttpClient httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(url);
string jsonResponse = await httpResponse.Content.ReadAsStringAsync();
coinDatas = JsonConvert.DeserializeObject<List<Root>>(jsonResponse);
}
public class Coin
{
public string id { get; set; }
public string icon { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public int rank { get; set; }
public double price { get; set; }
public double priceBtc { get; set; }
public double volume { get; set; }
public double marketCap { get; set; }
public double availableSupply { get; set; }
public double totalSupply { get; set; }
public double priceChange1h { get; set; }
public double priceChange1d { get; set; }
public double priceChange1w { get; set; }
public string contractAddress { get; set; }
public int? decimals { get; set; }
}
public class Root
{
public List<Coin> coins { get; set; }
}
2
Answers
I’ve donloaded JSON from your url. It looks like this:
I suppose ytour problem in
coinDatas = JsonConvert.DeserializeObject<List<Root>>(jsonResponse);
line.You have only one root element, lit a list of them.
And, by the way, your code does not return any value.
I recommend you to rwerite your method to somewthing like this:
then you can use this method in Main (notice
async
word in this method too):if you just need a list of coins, you can change the code to this