2

我有class ASystem.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完全按照Aclass 创建 class 并填充它并序列化它而不是A,但我认为有更优雅的方法来做到这一点。

你能建议我怎么做吗?

4

2 回答 2

2

我认为您可以在此处使用“数据合同代理”(通过 IDataContractSurrogate 接口使用。)

数据契约代理是建立在您已经使用的数据契约模型之上的高级功能。它允许您在想要更改类型如何序列化、反序列化或(如果您正在处理 XML)投影到模式中的情况下进行类型自定义和替换。

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

希望这可以帮助!

于 2012-04-26T19:48:32.060 回答
1

JSON.Net 支持对标有IsReference=true.

这里有一个详细的演练:

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

于 2012-07-10T17:31:39.450 回答