2

I have a sample controller when called should return a serialised object with a list of Animals with all there properties dislayed. The trouble im facing is that its only serialising the property in the base class

Model

public class MyAnimals
    {
        public string Description { get; set; }

        public ICollection<Animal> Animals { get; set; }
    }

    public class Animal
    {
        public string Name { set; get; }
    }

    public class Dog: Animal
    {
        public string Says { get; set; } 
    }

    public class Cat : Animal
    {
        public string Likes { get; set; }
    }

Controller

    [HttpGet]
    public IActionResult Animals()
    {

        var animals = new MyAnimals()
        {
            Description = "My favorite animals",
            Animals = new List<Animal>()
            {
                new Cat()
                {
                    Name = "Tom",
                    Likes = "Cheese"
                },

                new Dog()
                {
                    Name = "Pluto",
                    Says = "Bark"
                }
            }

        };

        return Ok(animals);
    }

when the object is seralised its coming out like this

Current Response

{
    "description": "My favorite animals",
    "animals": [
        {
            "name": "Tom"
        },
        {
            "name": "Pluto"
        }
    ]
}

The required output im after should be like the below. Please tell me what im doing wrong

Required Response

{
    "description": "My favorite animals",
    "animals": [
        {
            "name": "Tom",
            "Likes": "Cheese"
        },
        {
            "name": "Pluto",
            "Says": "Bark"
        }
    ]
}
O'Neil Tomlinson
  • 702
  • 1
  • 6
  • 28

2 Answers2

1

For a .NET Core 3+ project, you need to install

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson

and use it in startup

services.AddControllers().AddNewtonsoftJson();

This will use JSON.NET as default serializer and you can get the desired response

{
  "description": "My favorite animals",
  "animals": [
    {
      "likes": "Cheese",
      "name": "Tom"
    },
    {
      "says": "Bark",
      "name": "Pluto"
    }
  ]
}
0

Serializing is the first part of your issue, deserializing would be the scond part. Caleb George and JuanR have pointed you in good direction and a way to solve the problem.

Other way to do that is to manualy serialize each animal and transport it in animals array vith names and values. Name would be type of animal and value serialized object...

kzendra
  • 31
  • 1
  • 5
  • This should be a comment, not an answer, particularly since there is already one out there. – JuanR Jun 04 '21 at 01:46