在声明为基类型时防止 JSON.net 序列化派生类型属性[重复]

问题描述 投票:0回答:2

鉴于:

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 中看到该名称),而不是运行时类型属性。如何做到这一点?

c# json json.net polymorphism
2个回答
1
投票

您可以尝试延长

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() 
    });

参考:合同解决者


0
投票

使用

[JsonIgnore]

class Human : Mammal
{
    [JsonIgnore] public string Name { get; set; }
}

这将打印:

{"Mammal":{"Age":12}}
© www.soinside.com 2019 - 2024. All rights reserved.