I have this simple model class which is defined like this:
public class CountryLanguage
{
public string Name { get; set; }
public string ShortName { get; set; }
public string Description { get; set; }
}
I have this Web API which return an IEnumerable of CountryLanguage:
[HttpGet]
public IEnumerable<CountryLanguage> Get()
{
List<CountryLanguage> list = new List<CountryLanguage>();
list.Add(new CountryLanguage());
list.Add(new CountryLanguage());
return list;
}
I have this class where I want to store the result of the Web API call:
public class ResponseResult<T>
{
public HttpStatusCode StatusCode { get; set; }
public string Message { get; set; }
public T Payload { get; set; }
}
And finally, here is the code calling the Web API :
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, actionToCallWithParameters);
var response = httpClient.SendAsync(request).Result;
ResponseResult<T> responseResult = new ResponseResult<T>();
responseResult.StatusCode = response.StatusCode;
responseResult.Message = response.Content.ReadAsStringAsync().Result;
responseResult.Payload = response.Content.ReadAsAsync<T>().Result;
return responseResult;
If the web API return a CountryLanguage object, I got no problem of storing this object into my generic type property payload.
But if the Web API returns an IEnumerable, I get this error :
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'CountryLanguage' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
My question is: Is it possible to "normalize" this code so I can store either an object or an IEnumerable into my payload property of type T?