Generic Method for REST Query

2

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

This method works flawlessly when calling an external API Rest return list. However, it gives an exception when the external API return object 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: Can not 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 (eg [1,2,3]) to deserialize correctly.

Although not very relevant, it follows an example of the return in% with% of% of 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"},
]
    
asked by anonymous 24.06.2017 / 22:03

1 answer

1

This error is giving you why this is just coming back:

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

In the above case the API is returning an object.

To not give the error, the right would be:

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

In this case above the API is returning a collection of objects with just 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 do not need to pass json to IEnumerable<T> to then move everything to list with .ToList() ;

You can directly read as a List<T> , thus:

var dados = response.Content.ReadAsAsync<List<T>>().Result;
    
25.06.2017 / 17:40