如何序列化从使用DataContract(IsReference = true)装饰的类派生的类? [英] How to serialize class that derives from class decorated with DataContract(IsReference=true)?

查看:298
本文介绍了如何序列化从使用DataContract(IsReference = true)装饰的类派生的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类A ,它是从 System.Data.Objects.DataClasses.EntityObject 派生的。
当我尝试使用

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);  

我遇到错误

TestController + A._Id'未标记为OptionalFieldAttribute,因此指示必须对其进行序列化。但是, TestController + A源自标有DataContractAttribute和IsReference设置为 True的类。 IsReference类上可能没有必需的数据成员。用OptionalFieldAttribute装饰'TestController + A._Id',或在适当的父类上禁用IsReference设置。

即使我装饰了 OptionalFieldAttribute 的字段

类型'TestController + A'无法序列化为JSON,因为其IsReference设置为 True。 JSON格式不支持引用,因为没有用于表示引用的标准化格式。要启用序列化,请在该类型或该类型的适当父类上禁用IsReference设置。

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

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.

您能建议我怎么做吗?

推荐答案

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

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

数据合同代理是一项高级功能,它基于您已经在使用的数据合同模型而构建。如果要更改类型的序列化,反序列化方式,或者(如果要处理XML的话)将其投影到架构中,可以使用它进行类型自定义和替换。

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.

在您的情况下,使用IDataContractSurrogate可以使您按类型或对象进行自定义JSON序列化和反序列化。 IDataContractSurrogate将提供在序列化和反序列化期间由DataContractSJsonerializer替换一种类型所需的方法,并且您可能希望为您的方案提供其他特殊中介类型。

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.

希望这会有所帮助!

这篇关于如何序列化从使用DataContract(IsReference = true)装饰的类派生的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆