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

使用Newtonsoft序列化仅输出根对象、忽略指定子属性的实现方法问询

解决方案

你可以通过自定义 DefaultContractResolver 实现无侵入式的属性忽略,不需要修改实体类加特性,仅调整序列化配置即可:


步骤1:自定义合约解析器

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;

public class IgnorePropertyContractResolver : DefaultContractResolver
{
    private readonly Type _targetEntityType;
    private readonly HashSet<string> _propertiesToIgnore;

    public IgnorePropertyContractResolver(Type targetEntityType, params string[] propertiesToIgnore)
    {
        _targetEntityType = targetEntityType;
        _propertiesToIgnore = new HashSet<string>(propertiesToIgnore, StringComparer.OrdinalIgnoreCase);
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        // 仅过滤目标类的指定属性
        if (property.DeclaringType == _targetEntityType && _propertiesToIgnore.Contains(property.PropertyName))
        {
            property.ShouldSerialize = _ => false;
        }
        return property;
    }
}

步骤2:配置到序列化设置

将自定义的解析器注入到 JsonSerializerSettings 中即可:

var jsonSerializerSettings = new JsonSerializerSettings() 
{ 
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    // 指定忽略State类的Cities属性
    ContractResolver = new IgnorePropertyContractResolver(typeof(State), nameof(State.Cities))
};
string resultJson = Newtonsoft.Json.JsonConvert.SerializeObject(state, jsonSerializerSettings);

输出效果

序列化后会自动去掉Cities属性,仅保留根对象字段:

{"name":"State 1","id":"265439108547260417","creationTimeUtc":1638876015097,"modificationTimeUtc":1638876015097}

如果需要全局生效,可将配置赋值给 JsonConvert.DefaultSettings,之后所有序列化操作都会自动生效。


内容的提问来源于stack exchange,提问作者Mofid.Moghimi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:24:00