序列化DataMember(名称)覆盖问题 [英] Serialization DataMember (name) override issue

查看:210
本文介绍了序列化DataMember(名称)覆盖问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DataContractJsonSerializer,但DataMember名称有问题.

I am using a DataContractJsonSerializer and have an issue with the DataMember Name.

我做了一个基类和几个派生类.我需要派生类,因为我有不同的json字符串.我想反序列化json字符串,因此需要为数据成员使用不同的名称.我尝试更改DataMember的名称,如以下示例所示:

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:

基类:

[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名称(在我的情况下,这对于几个派生类是不同的).

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

另一个问题.我发现在基类上添加了KnownType并在派生类上添加了示例.对我来说似乎可以在派生类上做到这一点(尤其是对于继承问题).什么是正确的?

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?

推荐答案

我遇到了同样的问题.我使用的是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.

public class DerivedClass
{
    [DataMember(Name = "first_method")]
    new public string FirstMethod { get; protected set; }
}

这篇关于序列化DataMember(名称)覆盖问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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