My problem is that I want to deserialize the json object for a C # object, but the trick is that the C # object contains a List <abstract class>, and this abstract class is a superclass of 10 more classes.
public sealed class SearchAPIResult { public string Status; public SearchAPIQuery Query; public SearchResults Result; public SearchAPIResult() { } public SearchAPIResult(string status) { Status = status; } }
and SearchAPIResult :
public sealed class SearchResults { public string TextAnswer; public List<APIResultWidget> Items; public SearchResults() { Items = new List<APIResultWidget>(); } }
here, the APIResultWidget object is an abstract class, which inherits about 10 classes.
The problem is that the JSON object does not have something automatic (e.g. typeNameHandling in JSON.NET) to direct the deserializer to which the object of the 10 derived classes belongs. instead, objects are marked with two fields: Type and SubType ... like the following
{ "Status": "OK", "Query": { "Query": "this is a query", "QueryLanguage": "EN" }, "Result": { "TextAnswer": "This is your text answer", "Items": [{ "Type": "list", "SubType": null, "Title": null, "Items": [] }, { "Type": "text", "Content": "this is some content" } ] } }
in the previous json object, the result list contains two objects, one:
{ "Type": "list", "SubType": null, "Title": null, "Items": [] }
which maps to a class of type listWidget (which inherits from the abstract APIResultWidget and two:
{ "Type": "text", "Content": "this is some content" }
which maps to the textWidget class, which also inherits from the same abstract class
when i use the json.net method
SearchAPIResult converted = (SearchAPIResult)JsonConvert.DeserializeObject(json, typeof(SearchAPIResult), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto });
it throws the following exception:
Failed to create an instance of type Kngine.API.APIResultWidget. A type is an interface or abstract class and cannot be created. Path 'Result.Items [0] .Type', line 1, position 136.
I assume that there is a special way to indicate that this type is defined by both Type and SubType fields and provides the converter with this custom type annotator, is this true?