序列化 DataMember(名称)覆盖问题
我正在使用 DataContractJsonSerializer,并且 DataMember 名称有问题。
我创建了一个基类和几个派生类。我需要派生类,因为我有不同的 json 字符串。我想反序列化 json 字符串,因此需要为数据成员使用不同的名称。我尝试更改 DataMember 名称,如下例所示:
基类:
[DataContract]
public abstract class BaseClass
{
[DataMember]
public virtual string FirstMethod { get; protected set; }
}
派生类:
[DataContract]
[KnownType(typeof(BaseAccess))]
public class DerivedClass
{
[DataMember(Name="first_method")]
public virtual string FirstMethod { get; protected set; }
}
问题是,当我使用派生类时,序列化似乎忽略给定的 DataMember 名称。因此,当我使用 DerivedClass 类型进行反序列化时,序列化似乎是使用名称“FirstMethod”(基类)而不是“first_method”(派生类)进行的。是否可以使用派生类的 DataMember 名称(在我的情况下,这对于几个派生类来说是不同的)。
另一个问题。我找到了在基类上添加了 KnownType 并在派生类上添加了 KnownType 的示例。在我看来,在派生类上执行此操作似乎是合乎逻辑的(特别是对于继承问题)。什么是正确的?
I am using a DataContractJsonSerializer and have an issue with the DataMember Name.
I made a base class and several derived classes. I need the derived classes because I have different json strings. I want to deserialize the json strings and therefore need different names for the datamembers. I try to change the DataMember name as in the following example:
Baseclass:
[DataContract]
public abstract class BaseClass
{
[DataMember]
public virtual string FirstMethod { get; protected set; }
}
Derived class:
[DataContract]
[KnownType(typeof(BaseAccess))]
public class DerivedClass
{
[DataMember(Name="first_method")]
public virtual string FirstMethod { get; protected set; }
}
Problem is that when I use a derived class the serialization seems to ignore the given DataMember name. So when I deserialize with the type DerivedClass the serialization seems to take place with the name "FirstMethod" (of the base class) instead of "first_method" (of the derived class). Is it possible to use the DataMember name of the derived class (which is different for several derived classes in my situation).
Another question. I found examples with KnownType added on the base class and added on the derived class. Seems logic to me to do it on the derived class (espcially for inheritance concerns). What is correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也有同样的问题。我使用的是 VB.NET,并且必须隐藏(或重载)该属性以使 WCF 尊重派生类中的 DataMember 属性。在 C# 中,您应该能够使用 new 运算符。
I had this same issue. I was using VB.NET and I had to Shadow (or Overload) the property to get WCF to respect the DataMember property in my derived class. In C# you should be able to use the new operator.
诀窍是为基类的虚拟数据成员指定
EmitDefaultValue = false
,并在派生类的实现中返回默认值,以便数据成员不会被序列化。在派生类中定义另一个具有所需名称的数据成员。The trick is to specify
EmitDefaultValue = false
for the base class's virtual data member, and in its implementation in the derived class return default value so the data member is not serialized. In the derived class define another data member with the required name.