You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止Json.NET序列化声明为基类型的派生类属性

仅序列化基类Mammal属性的解决方案

针对你遇到的Newtonsoft.Json序列化时包含子类额外属性的问题,以下是几种可行的实现方式:

方法1:序列化时显式指定基类类型

如果只需单独序列化Mammal部分,直接将对象转换为基类类型后序列化即可:

// 仅序列化Mammal的属性
Console.WriteLine(JsonConvert.SerializeObject((Mammal)stuff.Mammal));
// 输出结果:{"Age":12}

若要序列化整个Stuff对象且保留基类属性,可使用自定义契约解析器。

方法2:自定义契约解析器

创建一个契约解析器,强制让Mammal的子类使用基类的序列化契约:

public class BaseTypeOnlyContractResolver : DefaultContractResolver
{
    protected override JsonContract CreateContract(Type objectType)
    {
        // 若当前类型是Mammal的子类,使用基类Mammal的序列化契约
        if (typeof(Mammal).IsAssignableFrom(objectType) && objectType != typeof(Mammal))
        {
            return base.CreateContract(typeof(Mammal));
        }
        return base.CreateContract(objectType);
    }
}

使用该解析器进行序列化:

var settings = new JsonSerializerSettings
{
    ContractResolver = new BaseTypeOnlyContractResolver()
};
Console.WriteLine(JsonConvert.SerializeObject(stuff, settings));
// 输出结果:{"Mammal":{"Age":12}}

这种方式灵活性高,不会影响类的原有特性标记。

方法3:使用特性标记控制序列化范围

在基类Mammal上启用选入式序列化,仅标记需要序列化的基类属性:

[JsonObject(MemberSerialization.OptIn)]
class Mammal
{
    [JsonProperty]
    public int Age { get; set; }
}

class Human : Mammal
{
    // 未标记[JsonProperty],不会被序列化
    public string Name { get; set; }
}

直接序列化即可得到目标结果:

Console.WriteLine(JsonConvert.SerializeObject(stuff));
// 输出结果:{"Mammal":{"Age":12}}

这种方式适合全局需要固定序列化基类属性的场景。

内容的提问来源于stack exchange,提问作者Node.JS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:03:27