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

不使用[JsonIgnore],如何让System.Text.Json将conts序列化为null

解决System.Text.Json序列化时让ContactType的conts属性显示为null的方案(无需[JsonIgnore])

以下是几种无需在实体类上加[JsonIgnore]属性的实现方式:

方法一:自定义JsonConverter

针对ContactType类编写自定义转换器,序列化时强制将conts属性设为null:

public class ContactTypeConverter : JsonConverter<ContactType>
{
    public override ContactType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        // 反序列化逻辑保持默认,如需自定义可调整
        return JsonSerializer.Deserialize<ContactType>(ref reader, options);
    }

    public override void Write(Utf8JsonWriter writer, ContactType value, JsonSerializerOptions options)
    {
        // 创建匿名对象复制ContactType属性,仅将conts设为null
        var serializedObj = new
        {
            value.Id,
            value.TypeName,
            // 补充ContactType的其他属性
            conts = (ICollection<Contact>)null
        };
        JsonSerializer.Serialize(writer, serializedObj, options);
    }
}

在序列化配置中注册该转换器:

var jsonOptions = new JsonSerializerOptions
{
    ReferenceHandler = ReferenceHandler.IgnoreCycles,
    Converters = { new ContactTypeConverter() }
};

var serializedResult = JsonSerializer.Serialize(yourLoadedData, jsonOptions);

方法二:序列化前手动置空(简单直接)

针对特定场景,可在序列化前遍历数据,手动将ContactType的conts设为null:

// 假设已通过Include加载完关联数据
foreach (var emp in empDataList)
{
    foreach (var contact in emp.Contacts)
    {
        contact.ContactType.conts = null;
    }
}

// 执行序列化
var json = JsonSerializer.Serialize(empDataList, new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.IgnoreCycles });

方法三:EF Core查询时用投影(从源头避免加载)

如果业务上不需要conts数据,可直接在EF Core查询阶段通过投影排除该属性,序列化时自然不会包含:

var empList = await dbContext.Emp
    .Include(e => e.Contacts)
    .ThenInclude(c => c.ContactType)
    .Select(e => new 
    {
        e.Id,
        e.Name,
        // 补充Emp的其他属性
        Contacts = e.Contacts.Select(c => new 
        {
            c.Id,
            c.Phone,
            // 补充Contact的其他属性
            ContactType = new 
            {
                c.ContactType.Id,
                c.ContactType.TypeName
                // 不包含conts属性,序列化时该字段为null或不出现
            }
        })
    })
    .ToListAsync();

var json = JsonSerializer.Serialize(empList, new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.IgnoreCycles });

内容的提问来源于stack exchange,提问作者A.Wasseem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:03:27