3

I have a simple model that I try to serialize to JSON, but some properties don't get included in the result. When my object inherits from a base class, the properties of the base class doesn't appear in the json.

In the JSON string "searchModel" is {}

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",

                ..........

In Visual Studio each item in the collection contains AssetsDefaultSearchModel with values in both properties: enter image description here

SteinTheRuler
  • 3,549
  • 4
  • 35
  • 71

2 Answers2

2

add below code to your Startup.cs

services.AddControllers().AddNewtonsoftJson();

you can use the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package

1

In the interface derived from ISearchResultBase I had to define a new property with the new keyword. I then return an object derived from IAssetsDefaultSearchResult (without replicating the property in the class) and it worked as expected.

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

    string DisplayName { get; }

    object Data { get; }

    TagBuilder HtmlTag { get; }
}
SteinTheRuler
  • 3,549
  • 4
  • 35
  • 71