There are a lot of similar questions on SO, but none of the ones I've read over the last two days seemed to help me.
I am using a public api to retrieve complex json objects. The response is rather predictable and I have the following generic class for the main response:
using Newtonsoft.Json;
using System.Collections.Generic;
namespace publicapi {
public class ApiGenericResponse<T> {
public string Get { get; set; }
public Dictionary<string, string> Parameters { get; set; }
public List<object> Errors { get; set; }
public int Results { get; set; }
public Paging Paging { get; set; }
public T Response { get; set; }
//public List<T> Response { get; set; }
}
}
The generic class is used during deserialisazing and the T
that is expected is where I am having trouble. Most of the time the Response
is an Array[Object]
and everything was going great up until the response received is an Object
and everything started crying over it.
When the public class ApiGenericResponse<T>
is expecting List<T> Response
, and it receives an array of objects, it works great up until there's an object instead.
ApiGenericResponse<ApiFixResponse> fixResp = JsonConvert.DeserializeObject<ApiGenericResponse<ApiFixResponse>>(string JasonContent);
- Gives me a usable deserialized List to work with.
..<ApiStatResponse> statResp
throws the following exception when trying to deserialize:
Now I know why it is complaining but my question is about getting past this hurdle.
The response and objects have their own class files thanks to https://json2csharp.com/
- There are too many to list here but it's all there and fine.
I like the list response as there are several ListBoxes that get populated with certain data, the single response won't be going into a ListBox but onto various controls.
How can I deserlialize these APIs correctly and use their methods and properties from the various classes that make up the objects?
One thing I have found was JsonConverter
and thought to convert the Response into an Array of 1 object.
..but I have absolutely no idea how it works. There isn't very many videos using Newtonsoft.Json. I would really appreciate help in understanding how it all works, whether and explanation or links to articles that do explain.
Mainly, I would like to know how to handle the various T Response
types
Thank you in advance.