I am using the WCF JSON serializer to produce JSON for use as return data for the ASP.NET MVC framework. I am doing this because the built-in JsonAction does not provide any way to control the naming of public properties in the serialized 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()));
}
}
In this example, I am using this with OpenFlashChart, so I set this.Data to a PieChart instance. It worked fine. Then, I set this.Data to an instance of Chart, and I got the following exception:
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.
Obviously, when I gave the serializer a PieChart
element, it was able to infer that I needed the Pie class as well. Why when I provide it Chart<PieChart>
is it no longer looking at the classes used by PieChart
? Is there a way to get around this issue without having to annotate everything with KnownTypeAttributes
?