I'm trying to connect with an external API. It gives me the results in JSON and depending my search term, it could give zero, one or more-than-one results.
I have mapped this to a C# class as follows:
Class Item
- List<ItemResult> Results { get; set; }
- Other properties, such as Name or Description (strings)
Whenever the JSON has an array of ItemResult (marked with []), it works fine, when the JSON has a single ItemResult (marked with {}), the parsing gives an error, because it expects a collection or array.
My request is done as follows:
private T DoRequest<T>(string url)
{
try
{
var webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Method = "GET";
webRequest.Accept = "application/json";
webRequest.UserAgent = UserAgent;
var webResponse = webRequest.GetResponse();
using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
{
var responseResult = streamReader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(CorrectJson(responseResult));
}
}
catch (Exception e)
{
UtilityBL.LogError(e.Message);
return default(T);
}
}
My question is: how can I make sure that this code handles both JSON results with an array of ItemResults as well as a single ItemResult? Perhaps I need to manually adjust the JSON result?
Thanks!
Edit:
it's similar to this question, but instead of JQuery or Javascript, I need a .NET solution: How to read both single object & array of objects in json using javascript/jquery
I have also tried following code, but it fails since JsonConvert tells me there now are 2 Album matches:
public class Albummatches
{
[JsonProperty("Album")]
public List<Album> Albums { get; set; }
[JsonProperty("Album")]
public Album Album {
set
{
Albums = new List<Album>();
Albums.Add(value);
}
}
}