Consuming API with Refit C#

Asked

Viewed 171 times

0

Good guys, I’m having a little problem consuming an API.

I am with an Aspnetmvc web application and need to consume an API.

First with a user selection I run this method below in the controller:

[HttpPost]
    public JsonResult ChamadaTrade(String valor)
    {
        if (valor != null)
        {
            var saida = APICalling.Call();
            return Json(saida);
        }
        else
        {
            var saida = "falha";
            return Json(saida);
        }
    }

The intereface for the implementation of the call:

 public interface IApiService
{
    [Get("")]
    Task<Data> GetDataAssync();
}

And the method that implements it:

[HttpGet("")]
    public static async Task<string> Call()
    {
        try
        {
            IApiService ExchangeClient = RestService.For<IApiService>("https://api.coinlore.net/api/tickers/");
            var dataExchange = await ExchangeClient.GetDataAssync();
            return dataExchange.Name.ToString();
        }
        catch (Exception e)
        {
            return $"Erro na consulta dos dados " + e.Message;
        }
    }

Yet I’m getting Jsonexception "jsonexception a possible Object Cycle was Detected which is not supported"

I just wanted to know if my code has some wrong implementation or if I need to do some JSON conversion that I’m not doing.

  • Hello, it’s a JSON setup. Your object is probably circular referenced Ex.: class Parent { public List<Child> children {get;set; } and class Child { public Parent {get;set; }; When the program will transform the object into JSON string, it will loop between the references of the two objects. You will need to ignore the error in the object serialize to avoid this type of circular reference.

1 answer

0


As Anderson Koester has already said, possibly his Data class is in circular reference. It should be something like this example:

public class Data {
    public string id { get; set; } 
    public string symbol { get; set; } 
    public string name { get; set; } 
    public string nameid { get; set; } 
    public int rank { get; set; } 
    public string price_usd { get; set; } 
    public string percent_change_24h { get; set; } 
    public string percent_change_1h { get; set; } 
    public string percent_change_7d { get; set; } 
    public string price_btc { get; set; } 
    public string market_cap_usd { get; set; } 
    public double volume24 { get; set; } 
    public double volume24a { get; set; } 
    public string csupply { get; set; } 
    public string tsupply { get; set; } 
    public string msupply { get; set; } 
}

public class DataResponse    {
    public List<Data> data { get; set; } 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.