0

I want to get data from API from https://rapidapi.com/coinlore/api/coinlore-cryptocurrency/

The result look like:

{2 items 
    "data":[...]100 items
    "info":{...}2 items
}

When I see it this way, I'm not sure how to create objects.

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 ?

The exception message is:

    ex  {Java.Net.UnknownHostException: Unable to resolve host "coinlore-cryptocurrency.p.rapidapi.com": No address associated with hostname ---> Java.Lang.RuntimeException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)    --- End of inne…} 
Ben Johnson
  • 753
  • 1
  • 9
  • 18
  • 1
    What the exception (in the `ex`) says? – Dmitry Dec 19 '21 at 23:32
  • Ben, it is not good idea to post your secrets (like API key) in public websites. It can be great community here, but someone could take an advantage on this. So please edit your code and remove that API key – Adam Lihm Dec 19 '21 at 23:48
  • Isn't `body` `Exchange`? So you should deserialize `JsonConvert.DeserializeObject(body);` and not `List`? – Adam Lihm Dec 19 '21 at 23:50
  • First, you can see the raw view of the data in your browser or using any number of free tools. Second, don't tell us that you "see the exception" without telling us **exactly what the exception is**. Third, you can use VS or a tool like json2csharp.com to translate json into C# classes. – Jason Dec 20 '21 at 01:12
  • When I use JsonConvert.DeserializeObject(body); I see the data in "body" and when step over to the next line exchange = exchangeBody; -> the debugger skip this line and go to exception. I update the question with exception message. – Ben Johnson Dec 20 '21 at 14:42

2 Answers2

1

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

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
1

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<Exchange>(body);
exchange = exchangeBody;
ColeX
  • 14,062
  • 5
  • 43
  • 240