我有下面的代码,它从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;
}
CMLanding页面:
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 中使用NewtonJSON.NET的多态串行化