我的代码就像这样
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
个对象,而且我会丢失信息)
答案 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"}
答案 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)。但我担心配置会因你的需要而变得复杂。