Reputation: 131
I have the below code that tries to get the Appication object from the web api service. I get the follwoing exception :
InnerException = {"Could not create an instance of type BusinessEntities.WEB.IApplicationField. Type is an interface or abstract class and cannot be instantated. Path '_applicationFormsList[0]._listApplicationPage[0]._listField[0]._applicationFieldID', line 1, position 194."}.
I do not understand why changing the FieldList to an Interface is causing problems in deserializing the object. Any pointers are much appreciated.
Task<HttpResponseMessage> task = HttpClientDI.GetAsync(someUri);
HttpResponseMessage response = task.Result;
HttpClientHelper.CheckResponseStatusCode(response);
try
{
Application application = response.Content.ReadAsAsync<ApplicationPage>().Result;
return application;
}
catch (Exception ex)
{
throw new ServiceMustReturnApplicationException(response);
}
[Serializable]
public class ApplicationPage
{
#region Properties
public int PageOrder { get; set; }
public string Title { get; set; }
public string HtmlPage { get; set; }
public int FormTypeLookupID { get; set; }
List<IApplicationField> _listField = new List<IApplicationField>();
public List<IApplicationField> FieldList
{
get { return _listField; }
set { _listField = value; }
}
}
Upvotes: 2
Views: 2641
Reputation: 75316
You need to specify the concrete classes for all the interfaces of the class which you are trying to deserialize so as to create the instances for these interface during deserialization process.
By doing this, it can be obtained by creating customized converter for json.net:
public class ApplicationFieldConverter : CustomCreationConverter<IApplicationField>
{
public override IApplicationField Create(Type objectType)
{
return new FakeApplicationField();
}
}
And your code should be:
string jsonContent= response.Content.ReadAsStringAsync().Result;
Application application = JsonConvert.DeserializeObject<Application>(jsonContent,
new ApplicationFieldConverter());
Note: The method Content.ReadAsAsync<...>()
is not found in ASP.NET Web API RC, you are using the beta version?
Upvotes: 2
Reputation: 142174
A serializer cannot deserialize any object graph that contains an interface because it doesn't know what concrete class to instantiate when re-hydrating the object graph.
Upvotes: 1