【问题标题】:inherited class and properties not included in JSON result from ASP.NET Core API来自 ASP.NET Core API 的 JSON 结果中未包含的继承类和属性
【发布时间】:2019-12-19 07:14:16
【问题描述】:

我有一个简单的模型,我尝试将其序列化为 JSON,但某些属性未包含在结果中。当我的对象继承自基类时,基类的属性不会出现在 json 中。

在 JSON 字符串中“searchModel”是 {}

SearchModelBase.cs

public interface ISearchModelBase
{
    SearchTypes Type { get; set; }
    string SearchString { get; set; }
}

public abstract class SearchModelBase : ISearchModelBase
{
    public SearchModelBase(SearchTypes type, string searchString)
    {
        this.Type = type;
        this.SearchString = searchString;
    }

    public SearchTypes Type { get; set; }

    public string SearchString { get; set; }
}

public enum SearchTypes
{
    User,
    Site
}

AssetsDefaultSearchModel.cs

public interface IAssetsDefaultSearchModel : ISearchModelBase
{

}

public class AssetsDefaultSearchModel : SearchModelBase, IAssetsDefaultSearchModel
{
    public AssetsDefaultSearchModel(SearchTypes type, string searchString) : base(type, searchString) 
    {

    }
}

JSON

{
    "items": [
        {
            "displayName": "FFU Samarin",
            "data": {
                "appId": 3,
                "displayName": "FFU Samarin",

                ..........

在 Visual Studio 中,集合中的每个项目都包含 AssetsDefaultSearchModel,并且在两个属性中都有值:

【问题讨论】:

  • 这是 .net-core-3 吗?您使用的是哪个序列化库?

标签: c# json asp.net-core asp.net-apicontroller


【解决方案1】:

在派生自 ISearchResultBase 的接口中,我必须使用 new 关键字定义一个新属性。然后我返回一个从 IAssetsDefaultSearchResult 派生的对象(不复制类中的属性),它按预期工作。

public interface IAssetsDefaultSearchResult : ISearchResultBase
{
    new ISearchModelBase SearchModel { get; }

    string DisplayName { get; }

    object Data { get; }

    TagBuilder HtmlTag { get; }
}

【讨论】:

    【解决方案2】:

    将以下代码添加到您的 Startup.cs

    services.AddControllers().AddNewtonsoftJson();
    

    您可以使用Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 2019-09-05
      • 2018-01-15
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      相关资源
      最近更新 更多