2012-07-31 55 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中找到,您正在使用測試版?

相關問題