The Web API interface returns a gesture understanding of the implementation class collection

The Web API interface returns a gesture understanding of the implementation class collection

The. NET Web API interface returns a list of base classes, and the test interface only returns the attributes of the base classes. How to return the attributes of the implementation classes?

最后更新 3/19/2023 8:55 PM
沙漠尽头的狼
预计阅读 4 分钟
分类
ASP.NET Core
标签
.NET C# ASP.NET Core Web API

Hello everyone, I am a wolf at the end of the desert.

I. problem description

As shown in the figure below, define two subclasses, Student and Deploy, both of which inherit from the abstract class PersonBase:

public abstract class PersonBase
{
    public string Name { get; set; }

    protected PersonBase(string name)
    {
        Name = name;
    }
}

public class Student : PersonBase
{
    public string Number { get; set; }

    public Student(string name, string number) : base(name)
    {
        Number = number;
    }
}

public class Employ : PersonBase
{
    public string CompanyName { get; set; }

    public Employ(string name, string companyName) : base(name)
    {
        CompanyName = companyName;
    }
}

Add a Web API interface to return a collection of base classes:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet(Name = "GetDetails")]
    public IEnumerable<PersonBase> Get()
    {
        return new List<PersonBase>()
        {
            new Student("学生A", "学生号01"),
            new Employ("职员01", "百度")
        };
    }
}

Interface return value:

[
  {
    "name": "学生A"
  },
  {
    "name": "职员01"
  }
]

Did you find the problem? The extended attributes of the Student class and the Deploy class instances (Student's Number attribute, Employ's Company attribute) are not serialized, so how to serialize all attributes of the subclass?

2. Implement serialization of all attributes of the class

参考微软文档《如何使用System.Text.Json序列化派生类的属性》,有两种实现方式站长觉得比较简单。

2.1 Implementation before. NET 7

In releases prior to. NET 7, System.Text.Json did not support serialization of polymorphic type hierarchies. For example, if the return value type of an interface is an interface or a collection of abstract classes, then even if the runtime type has other properties, only the properties defined for the interface or abstract class are serialized.

解决方案:将接口返回值由IEnumerable<PersonBase>改为object,接口实现的List<PersonBase>改为List<object>:

[HttpGet(Name = "GetDetails")]
public object Get()
{
    return new List<object>()
    {
        new Student("学生A", "学生号01"),
        new Employ("职员01", "百度")
    };
}

After modification, the interface successfully returned detailed JSON information:

[
  {
    "number": "学生号01",
    "name": "学生A"
  },
  {
    "companyName": "百度",
    "name": "职员01"
  }
]

** Principle: After changing ** to Object, the implementation class will be serialized by default. Before changing, System.Text.Json only knew the father of the implementation class.

2.2,. NET 7 and later implementations

Starting with. NET 7, System.Text.Json supports serialization and deserialization of polymorphic type hierarchies using feature annotations.

We restore the interface and add features to the abstract class to indicate the subclass types that need to be mapped when the base class is serialized:

[JsonDerivedType(typeof(Student))]
[JsonDerivedType(typeof(Employ))]
public abstract class PersonBase

The problem was solved, and the interface return value was the same as above.

文档关于JsonDerivedTypeAttribute的描述:当放置在类型声明中时,则指示应选择指定的子类型进行多态序列化。 它还公开用于指定类型鉴别器的功能。

3. Summary

上面两种方式看.NET版本选择,第二种方式需要您明确知道子类类型,详细使用请看微软文档:如何使用System.Text.Json序列化派生类的属性

If you have a better way, please leave a message and discuss it.

  • WeChat technical exchange group: Add WeChat (codewf) comment "Join the group"
  • QQ technical exchange group: 771992300.

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 6/22/2022

Localization of ASP.NET Core WebAPI (single resource file)

Microsoft's default method is that one class corresponds to multiple resource files, which is quite troublesome to use. This article introduces the use of single resource files, that is, all classes of the entire project correspond to a set of multi-language resource files.

继续阅读
同分类 / 同标签 4/13/2022

ASP.NET Core WebApi returns results Unified packaging practices

When WebApi unifies the return of results, I also thought further. First, how to better limit the return of unified formats, and secondly, the packaging of results must be simpler and more powerful. Through constant thinking and improvement, I finally had preliminary results, so I shared them. There was no end to learning and there was no end to thinking. I hope that I can share encouragement with you in this way.

继续阅读