How to serialize class that derives from class dec

2019-07-24 18:06发布

问题:

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/