Property from a superinterface missing when convert Interface to json

Viewed 41

I have created a simple Controller, that gives some dummy users to frontend.

 private readonly List<IUser> dummyUsers = new List<IUser> {
        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"
        }
    };

    // GET: UserController
    [HttpGet]
    [Route("")]
    public ActionResult GetUser()
    {
        return Ok(dummyUsers);
    }

The dummy users are the implement of an Interface called IUser

public interface IUser : IEmailProvider
{
    string Name { get; set; }

    int Age { get; set; }
}

Iuser inherits the Property "Email" from IEmailProvider

public interface IEmailProvider
{
    public string Email { get; set; }
}

And use postman i can only retrieve the name and age properties of User, the Email property are missing.

[postman httpget][1]

What's the problem here and how can I solve it? [1]: https://i.stack.imgur.com/pk1Vh.png

1 Answers

You are using system.text.json, I highly recommend you to use Newtonsof.Json instead. Install Microsoft.AspNetCore.Mvc.NewtonsoftJson and fix your program (or startup) file

using Newtonsoft.Json.Serialization;

builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
  options.SerializerSettings.ContractResolver =
        new CamelCasePropertyNamesContractResolver());

Or if it is possible, just use a class instead of the interface and system.text.json will work correctly:

var dummyUsers = new List<User> {....
Related