Home > OS >  How to figure out how to create objects relative to an api point using c#
How to figure out how to create objects relative to an api point using c#

Time:12-20

I want to get data from API from Data from API

I want to get data array and I create a objects like this:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace SmartCryptoWorld.Models
{
    public class Exchange
    {
        [JsonProperty("data")]
        public List<ExchangeBody> CryptoExchange { get; set; }
    }

    public class ExchangeBody
    {
        [JsonProperty("symbol")]
        public string Symbol { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("price_usd")]
        public double Price { get; set; }

        [JsonProperty("percent_change_24h")]
        public double Percent_Change_24h { get; set; }

        [JsonProperty("percent_change_1h")]
        public double Percent_Change_1h { get; set; }

        [JsonProperty("percent_change_7d")]
        public double Percent_Change_7d { get; set; }

        [JsonProperty("market_cap_usd")]
        public double Market_Cap_USD { get; set; }
    }
}

This is the method who works but the data not come in the List and go to catch exception:

 private async Task GetExchange()
    {
        try
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri("https://coinlore-cryptocurrency.p.rapidapi.com/api/tickers/?start=0&limit=100"),
                Headers =
                {
                    { "x-rapidapi-host", "coinlore-cryptocurrency.p.rapidapi.com" },
                    { "x-rapidapi-key", "51569aba99mshf9e839fcfce791bp16c0dbjsn9ced6dba7472" },
                },
            };
            using (var response = await client.SendAsync(request))
            {
                var exchange = new Exchange();
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
                
                var exchangeBody = JsonConvert.DeserializeObject<List<ExchangeBody>>(body);
                exchange.CryptoExchange = exchangeBody;
            }
        }
        catch (Exception ex)
        {
            await DisplayAlert("Alert", "Please, check your internet connection.", "OK");
        }
    }

In var body = await response.Content.ReadAsStringAsync(); I see the data from API, when I step over with debugger to next line var exchangeBody = JsonConvert.DeserializeObject<List<ExchangeBody>>(body); I see the catch exception..

So I'm 100% sure that the objects are not as they should be ?

CodePudding user response:

Well the most simple way of doing it is to copy a result of an API call (better if it has more items in the array) and use the Edit > Paste Special > Paste Json As Classes, now making a little changes you can have the classes you want.

Note: you need to check the class properties afterwards, for example if a property can be double but in your specific results it has a int value, paste special may consider this property as int while it's not (and other rare similar cases) and that is why I suggest having more array items for better accuracy.

And also note that "Paste Special" only appears on code files (.cs, .vb) and not in views, configuration files, etc.

enter image description here

CodePudding user response:

The json return from the request is an object not a list , you should deserialize the json as object not list.

Modify your code as below

var exchangeBody = JsonConvert.DeserializeObject<ExchangeBody>(body);
exchange = exchangeBody;
  • Related