gpt4 book ai didi

asp.net-core - 来自 ASP.NET Core API 的 JSON 响应中缺少派生类型的属性

转载 作者:行者123 更新时间:2023-12-04 11:08:24 24 4
gpt4 key购买 nike

我的 ASP.NET Core 3.1 API Controller 的 JSON 响应缺少属性。当属性使用派生类型时会发生这种情况;在派生类型中定义但不在基/接口(interface)中定义的任何属性都不会序列化为 JSON。似乎在响应中缺乏对多态性的支持,就好像序列化是基于属性的定义类型而不是其运行时类型一样。如何更改此行为以确保所有公共(public)属性都包含在 JSON 响应中?

示例:

我的 .NET Core Web API Controller 返回此对象,该对象具有接口(interface)类型的属性。

    // controller returns this object
public class Result
{
public IResultProperty ResultProperty { get; set; } // property uses an interface type
}

public interface IResultProperty
{ }

这是一个派生类型,它定义了一个名为 Value 的新公共(public)属性。 .

    public class StringResultProperty : IResultProperty
{
public string Value { get; set; }
}

如果我像这样从 Controller 返回派生类型:

    return new MainResult {
ResultProperty = new StringResultProperty { Value = "Hi there!" }
};

那么实际响应包含一个空对象( Value 属性缺失):

enter image description here

我希望得到的回应是:
    {
"ResultProperty": { "Value": "Hi there!" }
}

最佳答案

虽然其他答案很好并解决了问题,但如果您想要的只是一般行为就像 pre netcore3,您可以使用 Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包并在 Startup.cs 中执行以下操作:

services.AddControllers().AddNewtonsoftJson()
更多信息 here .这样,您不需要创建任何额外的 json 转换器。

关于asp.net-core - 来自 ASP.NET Core API 的 JSON 响应中缺少派生类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59308763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com