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

ASP.NET接口转JSON时父接口属性丢失的问题排查与解决

接口返回数据丢失Email属性的原因及解决方法

问题原因

ASP.NET Core默认使用的System.Text.Json序列化器,在序列化接口类型对象时,仅会序列化当前接口直接定义的属性,不会自动遍历并序列化父接口的属性。你的dummyUsers是List<IUser>类型,序列化时只会处理IUser接口内的Name和Age,而父接口IEmailProvider定义的Email属性会被忽略。

解决方法

方法1:改用具体实现类的集合类型

将dummyUsers的类型从List<IUser>改为List<User>,让序列化器直接处理具体类的所有属性(包括继承自父接口的Email):

private readonly List<User> dummyUsers = new List<User> {
    new User
    {
        Name = "Michael",
        Age = 34,
        Email = "michael@gmx.de"
    },
    new User
    {
        Name = "Nino",
        Age = 30,
        Email = "nino@gmx.de"
    },
    new User
    { 
        Name = "Wendy",
        Age = 27,
        Email = "Wendy@gmx.de"
    }
};

方法2:序列化时转换为具体类型集合

保持原集合类型不变,在返回数据前将接口集合转换为具体类集合:

[HttpGet]
[Route("")]
public ActionResult GetUser()
{
    return Ok(dummyUsers.Cast<User>());
}

方法3:通过特性标记接口的实现类型(.NET 6+)

在IUser接口上添加JsonDerivedType特性,指定其具体实现类,让序列化器识别到父接口的属性:

using System.Text.Json.Serialization;

[JsonDerivedType(typeof(User))]
public interface IUser : IEmailProvider
{
    string Name { get; set; }
    int Age { get; set; }
}

内容的提问来源于stack exchange,提问作者Min

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:35:30