不使用[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
相关产品推荐
相关产品推荐

