我有以下代码,尝试从 Web api 服务获取 Appication 对象。我收到以下异常:
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."}.
我不明白为什么将 FieldList 更改为 Interface 会导致反序列化对象时出现问题。非常感谢任何指点。
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; }
}
}
最佳答案
您需要为要反序列化的类的所有接口(interface)指定具体类,以便在反序列化过程中为这些接口(interface)创建实例。
这样做,可以通过为json.net创建自定义转换器来获取:
public class ApplicationFieldConverter : CustomCreationConverter<IApplicationField>
{
public override IApplicationField Create(Type objectType)
{
return new FakeApplicationField();
}
}
你的代码应该是:
string jsonContent= response.Content.ReadAsStringAsync().Result;
Application application = JsonConvert.DeserializeObject<Application>(jsonContent,
new ApplicationFieldConverter());
注意:方法Content.ReadAsAsync<...>()
在 ASP.NET Web API RC 中找不到,您使用的是 beta 版本吗?
关于c# - ReadAsAsync - 抛出异常类型是接口(interface)或抽象类,无法实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11748912/