鉴于:
class Mammal
{
public int Age { get; set; }
}
class Human : Mammal
{
public string Name { get; set; }
}
class Stuff
{
public Mammal Mammal { get; set; }
}
还有
var stuff = new Stuff
{
Mammal = new Human
{
Name = "test",
Age = 12
}
};
Console.WriteLine(JsonConvert.SerializeObject(stuff));
我得到:
{"Mammal":{"Name":"test","Age":12}}
但我只想获取静态定义的类型属性(这意味着我不应该在 JSON 中看到该名称),而不是运行时类型属性。如何做到这一点?
您可以尝试延长
DefaultContractResolver
:
public class MyContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
// Of course, the logic here is up to you!
if (objectType == typeof(Human))
{
return base.CreateContract(typeof(Mammal));
}
return base.CreateContract(objectType);
}
}
它只是说 - 如果序列化的对象是
Human
类型,则根据基类 Mammal
的约定对其进行序列化。这正是你想要的。那么应该像这样使用:
var stuff = new Stuff
{
Mammal = new Human
{
Name = "test",
Age = 12
}
};
var json = JsonConvert.SerializeObject(
stuff,
Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new MyContractResolver()
});
参考:合同解决者
使用
[JsonIgnore]
:
class Human : Mammal
{
[JsonIgnore] public string Name { get; set; }
}
这将打印:
{"Mammal":{"Age":12}}