4

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

1
  • 1
    Is this .net-core-3? Which serialization library are you using? Commented Dec 19, 2019 at 8:22

2 Answers 2

2

add below code to your Startup.cs

services.AddControllers().AddNewtonsoftJson();

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

Sign up to request clarification or add additional context in comments.

Comments

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; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.