How to serialize class that derives from class decorated with DataContract(IsReference=true)?

筅森魡賤 提交于 2020-01-04 05:13:52

问题


I have class A that derives from System.Data.Objects.DataClasses.EntityObject. When I try to serialize using

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

I get error

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.

Even if I decorate the field with OptionalFieldAttribute I get

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.

I cannot modify EntityObject class. I thought to create A_Bag class exactly as A class and fill it and serialize it instead of A, but I think there's more elegant way to do it.

Can you suggest how I can do it?


回答1:


I think you can use a "data contract surrogate" here (used via the IDataContractSurrogate interface.)

The data contract surrogate is an advanced feature built upon the Data Contract model you're already using. It lets you do type customization and substitution in situations where you want to change how a type is serialized, deserialized, or (if you're dealing with XML) projected into schema.

In your case, the use of IDataContractSurrogate lets you do custom JSON serialization and deserialization on a per-type or per-object basis. An IDataContractSurrogate would provide the methods needed to substitute one type for another by the DataContractSJsonerializer during serialization and deserialization, and you may want to provide a different "special" intermediary type for your scenario.

Hope this helps!




回答2:


JSON.Net supports serialization of objects marked with IsReference=true.

There is a detailed walkthrough here:

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



来源:https://stackoverflow.com/questions/8282761/how-to-serialize-class-that-derives-from-class-decorated-with-datacontractisref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!