如何从派生类中只获取基类属性?

时间:2017-06-23 14:39:22

标签: c# serialization json.net

我的代码就像这样

public class BaseClass
{
    public string Field1 { get; set; }
}

public class DerivedClass: BaseClass
{
    public string Field2 { get; set; }
}

var obj = new DerivedClass { Field1 = "aaa", Field2 = "bbb" };

我必须序列化obj,但我只需要BaseClass属性,因为DerivedClass属性是"其他信息"在反序列化后添加。

我怎样才能得到它们? (我不能使用[JSonIgnore]装饰器,因为我必须通过websocket发送DerivedClass个对象,而且我会丢失信息)

3 个答案:

答案 0 :(得分:4)

您可以定义一个自定义合约解析程序,用于过滤掉所有DerivedClass属性:

public class NoDerivedContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        property.ShouldSerialize = _ => property.DeclaringType != typeof(DerivedClass);
        return property;
    }
}

// .................

var obj = new DerivedClass { Field1 = "aaa", Field2 = "bbb" };
var json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { 
    ContractResolver = new NoDerivedContractResolver() 
});
Console.WriteLine(json);

// Output:
//    {"Field1":"aaa"}

演示:https://dotnetfiddle.net/Qailvp

答案 1 :(得分:3)

您可以为BaseClass提供一个构造函数,该构造函数将BaseClass作为参数并获取必要的信息。这样您就可以创建一个新对象并将其序列化:

public class BaseClass
{
    public string Field1 { get; set; }

    public BaseClass(){ }
    public BaseClass(BaseClass dc)
    {
        this.Field1 = dc.Field1;
    }
}

public class DerivedClass : BaseClass
{
    public string Field2 { get; set; }
}

这样称呼:

var obj = new DerivedClass { Field1 = "aaa", Field2 = "bbb" };

BaseClass obj_base = new BaseClass(obj);

答案 2 :(得分:2)

您是否无法映射包含所有数据的第三个类,如下所示:

public class BaseClass
{
    public string Field1 { get; set; }
}

public class DerivedClass: BaseClass
{
    public string Field2 { get; set; }
}

public class BaseClassDTO{
    public string Field1 { get; set; }
    public BaseClassDTO(BaseClass baseClass){
        this.Field1 = baseClass.Field1;
    }
}

有些人提议(https://github.com/quozd/awesome-dotnet#object-to-object-mapping)。但我担心配置会因你的需要而变得复杂。