Generic Method for REST Query

Asked

Viewed 308 times

2

I need to refactor this method to make it work better.

This method works perfectly when calling on an external API Rest returns list. However, it gives exception when the return object of the external API Rest returns an element only.

 public List<T> ChamarAPIListagem<T>(string chamada)
 {
     HttpResponseMessage response = client.GetAsync(chamada).Result;

     if (response.IsSuccessStatusCode)
     {
         var dados = response.Content.ReadAsAsync<IEnumerable<T>>().Result;
         return dados.ToList();
     }

     return null;
 }

The problem is when the API returns an object only. It gives exception error:

Jsonserializationexception: Cannot deserialize the Current JSON Object (e.g. {"name":"value"}) into type 'System.Collections.Generic.Ienumerable`1[Appspot.Ano]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

Although not very relevant, follows an example of the return in JSON of API external;

An example of an API return would be this:

[
    {"codigo": "320-1", "name": "Zer", "key": "320"},
    {"codigo": "201-1", "name": "201", "key": "201"},
    {"codigo": "201-1", "name": "201", "key": "201"},
    {"codigo": "201-1", "name": "201", "key": "201"},
]

1 answer

1


This mistake is making because it’s just coming back:

{"codigo": "320-1", "name": "Zer", "key": "320"}

In the above case the API is coming back an object.

In order not to make the mistake, the right one would be:

[{"codigo": "320-1", "name": "Zer", "key": "320"}]

Already in this case above the API is returning a collection of objects with only one item

If you know when the API will only return the object, you can create another method that reads the object, example

 public T ChamarAPI<T>(string chamada)
 {
     HttpResponseMessage response = client.GetAsync(chamada).Result;

     if (response.IsSuccessStatusCode)
     {
         var dados = response.Content.ReadAsAsync<T>().Result;
         return dados;
     }

     return null;
 }

And when it’s a collection you call the listing method.

Tip

You don’t need to pass the json to IEnumerable<T> to then pass everything to the list with the .ToList();

You can directly read as a List<T>, being like this:

var dados = response.Content.ReadAsAsync<List<T>>().Result;

Browser other questions tagged

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