2012-07-31 56 views
2

我有下面的代码,试图从Web API服务获取Appication对象。我得到的follwoing异常:ReadAsAsync - 抛出异常类型是一个接口或抽象类,不能立即

的InnerException = {“无法创建类型BusinessEntities.WEB.IApplicationField的一个实例类型是一个接口或抽象类,不能instantated路径“_applicationFormsList [0] ._ listApplicationPage [。 0] ._ listField [0] ._ applicationFieldID',line 1,position 194.“}。

我不明白为什么将FieldList更改为接口导致反序列化对象时出现问题。任何指针都非常感谢。

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; } 
    } 
} 

回答

1

序列化器无法反序列包含一个接口,因为它不知道具体的类时重新水合对象图实例化任何对象图。

2

您需要指定您试图反序列化的类的所有接口的具体类,以便在反序列化过程中为这些接口创建实例。

通过这样做,可以通过创建自定义的转换器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中找到,您正在使用测试版?

相关问题