簡體   English   中英

ReadAsAsync - 錯誤:“Type是一個接口或抽象類,無法實例化。”

[英]ReadAsAsync - Error : “Type is an interface or abstract class and cannot be instantiated.”

我有以下代碼從web api服務獲取對象。

在以下代碼行

response.Content.ReadAsAsync<CMLandingPage>().Result;

我得到以下異常:

InnerException = {"Could not create an instance of type MLSReports.Models.IMetaData. Type is an interface or abstract class and cannot be instantiated. Path 'BaBrInfo.Series[0].name', line 1, position 262."}

任何指針都非常感謝。

 CMLandingPage lpInfo = new CMLandingPage();

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // Add an Accept header for JSON format
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    response = client.PostAsJsonAsync(LPChartinfoapiURL, criteria.Mlsnums).Result;
                }
                // Throw exception if not a success code.
                response.EnsureSuccessStatusCode();
                // Parse the response body.
                lpInfo = response.Content.ReadAsAsync<CMLandingPage>().Result;
                }

CMLandingPage:

namespace MLSReports.Models
{
    public class CMLandingPage
    {
        public CMLandingPage()  {  }

        public CMColumn BaBrInfo { get; set; }

     }
  public class CMColumnItem<T> : IMetaData
    {
        #region Constructors and Methods
        public CMColumnItem()   {   }
        #endregion

        #region Properties and Fields
        public string name { get; set; }
        public List<T> data { get; set; }
        public string color { get; set; }
        #endregion

    }

    public class CMColumn
    {
        #region Constructor and Method
        public CMColumn()
        {
           Series = new List<IMetaData>();
        }
        #endregion

        #region Properties and Fields
        public string ChartType { get; set; }
        public string ChartTitle { get; set; }
        public List<IMetaData> Series { get; set; }
        #endregion    
    }
}

您的CmColumn類上有此屬性:

    public List<IMetaData> Series { get; set; }

WebApi控制器顯然試圖根據您發送它的參數值構造一個對象。 當它到達名為“BaBrInfo.Series [0] .name”的值時,它知道它應該創建一個新的IMetaData對象,以便它可以設置它的name並將其添加到Series屬性,但IMetaData只是一個接口:它不知道要構造什么類型的對象。

嘗試將IMetaData更改為實現該接口的某種具體類型。

您需要讓序列化程序在json有效負載和反序列化器中包含類型以使用包含的類型:

//Serialization
var config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
return Request.CreateResponse(HttpStatusCode.OK, dto, config);

//Deserialization
var formatter = new JsonMediaTypeFormatter
{
    SerializerSettings = { TypeNameHandling = TypeNameHandling.Auto }
};
response.Content.ReadAsAsync<CMLandingPage>(new [] { formatter }).Result;

在HTTPCONTENT中使用NEWTON JSON.NET的多態串行化

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM