【问题标题】:Serialising a Collection of objects that are using polymorphism (Base Class) [duplicate]序列化使用多态性的对象集合(基类)[重复]
【发布时间】:2021-08-21 00:54:25
【问题描述】:

我有一个示例控制器,在调用时应该返回一个带有动物列表的序列化对象,其中显示所有属性。我面临的问题是它只序列化基类中的属性

型号

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

控制器

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

当对象被序列化时,它会像这样出来

当前反应

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

im after 所需的输出应该如下所示。请告诉我我做错了什么

必填项

{
    "description": "My favorite animals",
    "animals": [
        {
            "name": "Tom",
            "Likes": "Cheese"
        },
        {
            "name": "Pluto",
            "Says": "Bark"
        }
    ]
}

【问题讨论】:

标签: c# asp.net json inheritance serialization


【解决方案1】:

对于 .NET Core 3+ 项目,您需要安装

安装包 Microsoft.AspNetCore.Mvc.NewtonsoftJson

并在启动时使用它

services.AddControllers().AddNewtonsoftJson();

这将使用 JSON.NET 作为默认序列化程序,您可以获得所需的响应

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

【讨论】:

    【解决方案2】:

    序列化是问题的第一部分,反序列化是第二部分。 Caleb George 和 JuanR 为您指明了正确的方向和解决问题的方法。

    另一种方法是手动序列化每只动物并将其传输到动物数组中,其中包含名称和值。名称将是动物类型和值序列化对象...

    【讨论】:

    • 这应该是一个评论,而不是一个答案,特别是因为那里已经有一个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2010-11-30
    相关资源
    最近更新 更多