【发布时间】:2010-01-08 16:03:39
【问题描述】:
我正在使用 WCF JSON 序列化程序来生成 JSON 以用作 ASP.NET MVC 框架的返回数据。我这样做是因为内置的 JsonAction 没有提供任何方法来控制序列化 JSON 中公共属性的命名。
public override void ExecuteResult(ControllerContext context)
{
...
if (Data != null)
{
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(Data.GetType());
System.IO.MemoryStream ms = new System.IO.MemoryStream();
serializer.WriteObject(ms, this.Data);
response.Write(Encoding.Default.GetString(ms.ToArray()));
}
}
在此示例中,我将它与 OpenFlashChart 一起使用,因此我将 this.Data 设置为 PieChart 实例。它工作得很好。然后,我将 this.Data 设置为 Chart 的一个实例,我得到了以下异常:
Type 'OpenFlashChart.Pie' with data contract name 'Pie:http://schemas.datacontract.org/2004/07/OpenFlashChart' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
显然,当我给序列化程序一个 PieChart 元素时,它能够推断出我也需要 Pie 类。为什么当我提供Chart<PieChart> 时,它不再查看PieChart 使用的类?有没有办法绕过这个问题而不必用KnownTypeAttributes 注释所有内容?
【问题讨论】:
标签: c# asp.net-mvc wcf json serialization