如何序列化派生自使用DataContract(IsReference = true)修饰的类的类?

时间:2011-11-27 00:37:10

标签: c#-4.0 datacontract jsonserializer datacontractjsonserializer

class A来自System.Data.Objects.DataClasses.EntityObject。 当我尝试使用

序列化时
var a = new A();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(a.GetType());
serializer.WriteObject(Response.OutputStream, a);  

我收到错误

TestController+A._Id' is not marked with OptionalFieldAttribute, thus indicating that it must be serialized. However, 'TestController+A' derives from a class marked with DataContractAttribute and an IsReference setting of 'True'. It is not possible to have required data members on IsReference classes. Either decorate 'TestController+A._Id' with OptionalFieldAttribute, or disable the IsReference setting on the appropriate parent class.

即使我用OptionalFieldAttribute装饰字段,我也会

The type 'TestController+A' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type.

我无法修改EntityObject课程。我想将A_Bag类与A类完全相同并填充并序列化而不是A,但我认为有更优雅的方法来实现它。

你能建议我怎么做吗?

2 个答案:

答案 0 :(得分:2)

我认为你可以在这里使用“数据合约代理”(通过IDataContractSurrogate接口使用。)

数据合同代理是基于您已使用的数据合同模型构建的高级功能。它允许您在需要更改类型的序列化,反序列化或(如果您正在处理XML)投射到模式中的方式时进行自定义和替换。

在您的情况下,使用IDataContractSurrogate可以基于每个类型或每个对象执行自定义JSON序列化和反序列化。 IDataContractSurrogate将提供在序列化和反序列化期间由DataContractSJsonerializer将一种类型替换为另一种类型所需的方法,并且您可能希望为您的方案提供不同的“特殊”中间类型。

希望这有帮助!

答案 1 :(得分:1)

JSON.Net支持标记为IsReference=true的对象的序列化。

这里有一个详细的演练:

http://dotnet.learningtree.com/2012/04/03/working-with-the-entity-framework-and-the-web-api/

相关问题