前言

假设有一个 Person 抽象基类,其中包含 Student 和 Teacher 派生类:

public class Person
{public string Name { get; set; }
}public class Student : Person
{public int Score { get; set; }
}public class Teacher : Person
{public string Title { get; set; }
}

如果 API 返回类型是单个 Person 抽象基类,System.Text.Json内置功能已经可以直接支持序列化派生类:

[HttpGet]
[Route("get")]
public Person Get()
{Person person = new Student { Name = "zhangsan", Score = 100 };return person;
}

c747a7e11407dd957c75e8f4bade47c4.png

但是,当 API 需要返回 Person 抽象基类的集合时,System.Text.Json就不知道如何处理了,即使集合内部只有一种派生类型:

[HttpGet]
[Route("list")]
public IEnumerable<Person> List()
{return new Person[] {new Student { Name = "zhangsan", Score = 100 }};
}

50ad43cb8c5fe99818037dde0e997895.png

可以看到,只处理了基类的属性。

我们必须主动告诉System.Text.Json如何处理序列化派生类,因此需要自定义转换器。

解决方案

为基类创建自定义转换器:

public class PersonConverter : JsonConverter<Person>
{public override Person Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options){throw new NotImplementedException();}public override void Write(Utf8JsonWriter writer, Person person, JsonSerializerOptions options){writer.WriteStartObject();if (person is Student student){writer.WriteNumber("score", student.Score);}else if (person is Teacher teacher){ writer.WriteString("title", teacher.Title);}writer.WriteString("name", person.Name);writer.WriteEndObject();}
}

然后修改 Startup.cs 文件,注册自定义转换器:

services.AddControllers().AddJsonOptions(options =>options.JsonSerializerOptions.Converters.Add(new PersonConverter()));

运行,序列化成功:

dd921eb2cb4b1577e995a3c09697db18.png

上面的转换器代码通过手动写入每个属性实现序列化,那属性一多还不要累死!

一种替代方法是调用System.Text.Json内置功能实现序列化单个派生类:

public override void Write(Utf8JsonWriter writer, Person person, JsonSerializerOptions options)
{JsonSerializer.Serialize(writer, (object)person, options);
}

注意,必须将要序列化的对象转换为 object

结论

通过自定义转换器,我们实现了使用System.Text.Json序列化派生类。

添加微信号【MyIO666】,邀你加入技术交流群

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/280816.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/280816.shtml
英文地址,请注明出处:http://en.pswp.cn/news/280816.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

OPC Client “failed to execute OPCENUM” 解决方法

进入cmd重新执行 OpcEnum.exe /regserver 即可。

django07: 模板语言(旧笔记)

详见&#xff1a;https://www.cnblogs.com/liwenzhou/p/7931828.html#autoid-2-3-6 包含&#xff1a; 模板 块 组件 静态文件

block,inline和inline-block概念和区别

block&#xff1a;block-level elements (块级元素) &#xff0c;inline&#xff1a; inline elements (内联元素)。block元素通常被现实为独立的一块&#xff0c;会单独换一行&#xff1b;inline元素则前后不会产生换行&#xff0c;一系列inline元素都在一行内显示&#xff0c…

Hadoop3.0 WordCount测试一直Accept 状态,Nodes of the cluster 页面node列表个数为0

起因是我运行wordcount测试一直卡主&#xff0c;不能执行&#xff0c;一直处于 Accept 状态&#xff0c;等待被执行&#xff0c;刚开始是各种配置yarn参数&#xff0c;以及host配置&#xff0c;后来发现还是不行 hadoop 集群安装完成后&#xff0c;在50070的 HDFS 管理后台能看…

nexus 手动增加_如何使用Google的工厂图像手动升级Nexus设备

nexus 手动增加Google’s Nexus devices are supposed to receive timely updates, but the staggered rollout means it can take weeks for devices to receive over-the-air (OTA) updates. Luckily, there’s a faster (and geekier) way to install the latest version of…

教你创建Google网站地图Sitemap.xml(转)

http://teachmyself.blog.163.com/blog/static/18881422920119895248288/ Sitemap.xml是 google搞出来的&#xff0c;也就是网站地图&#xff0c;不过这个网站地图是用xml写的&#xff0c;而且要按google的标准来写&#xff0c;并且要将写出来的这个文件 sitemap.xml上传到自己…

Oracle存储过程语法

创建基本的存储过程 1 CREATE OR REPLACE PROCEDURE MyProName IS 2 BEGIN 3 NULL; 4 END; 行1:CREATE OR REPLACE PROCEDURE 是一个SQL语句通知Oracle数据库去创建一个叫做skeleton存储过程, 如果存在就覆盖它; 行2:IS关键词表明后面将跟随一个PL/SQL体。 行3:BEGIN关键词表…

WPF-16 图形处理

我们这节主要介绍WPF常用画图标签&#xff0c;由于WPF图形处理设计大量篇幅 ,我们在这里抛砖引玉&#xff0c;具体更多的学习资料链接https://github.com/microsoft/WPF-Samples/tree/master/Graphics 该链接中微软提供了大量的学习Demo&#xff0c;WPF图形处理最大的区别在于…

powershell 文件/文件夹操作

新建文件夹 New-Item -ItemType Directory -Force -Path $TargetPath复制文件夹到另外文件夹 Copy-Item <源文件夹> <新文件夹> -recurse -force 复制文件&#xff08;与修改文件名&#xff09; // 达到复制文件到新文件夹&#xff0c;及修改文件名效果 copy-…

纯CSS制作各种各样的网页图标(三角形、暂停按钮、下载箭头、加号等)

三角形 <div class"box"></div> <style>.box{ width: 0;height: 0;border-top: 50px solid transparent;border-bottom: 50px solid transparent;border-left: 50px solid transparent;border-right: 50px solid red; } </style> 平行四边形…

您的MyFitnessPal帐户几乎肯定已被黑客入侵,请立即更改密码

If you’re one of the millions of the 150 million MyFitnessPal users, bad news: hackers have your email address, your user name, and your hashed password. 如果您是1.5亿MyFitnessPal用户中的数百万用户之一&#xff0c;那么这是个坏消息&#xff1a;黑客拥有您的电…

Oracle Grid 11.2.0.4 安装是出现INS-30510: Insufficient number of ASM disks selected.

最新文章&#xff1a;Virsons Blog 错误的原因是由于磁盘数和冗余层级不匹配&#xff1a; 如果创建用来存放OCR和VOTEDISK的ASM磁盘组&#xff0c;那么External、Normal、High三种冗余级别对应的Failgroup个数是1、3、5。也就是说&#xff0c;创建这三种冗余级别的磁盘组至少分…

动态编译库 Natasha 5.0 版本发布

动态编译库 Natasha 5.0 于十月份发布&#xff0c;此次大版本更新带来了强大的兼容性支持&#xff0c;目前 Natasha 已支持 .NET Standard 2.0 及 .NET Core 3.1 以上版本&#xff08;包括 .NET Framework&#xff09;了。引入项目NuGet\Install-Package DotNetCore.Natasha.CS…

著名软件公司的java笔试算法题!(含参考答案)

原题如下&#xff1a;用1、2、2、3、4、5这六个数字&#xff0c;用java写一个main函数&#xff0c;打印出所有不同的排列&#xff0c;如&#xff1a;512234、412345等&#xff0c;要求&#xff1a;"4"不能在第三位&#xff0c;"3"与"5"不能相连.…

django08: 视图与路由(旧笔记)

视图&#xff08;Views&#xff09; https://www.cnblogs.com/liwenzhou/articles/8305104.html 1.CBV和FBV 2.​​​​​上传文件示例 路由 https://www.cnblogs.com/liwenzhou/p/8271147.html 1.url正则表达 2.分组命名匹配&#xff08;参数&#xff09; 3.反向解析 …

【BZOJ1042】硬币购物(动态规划,容斥原理)

【BZOJ1042】硬币购物&#xff08;动态规划&#xff0c;容斥原理&#xff09; 题面 BZOJ Description 硬币购物一共有4种硬币。面值分别为c1,c2,c3,c4。某人去商店买东西&#xff0c;去了tot次。每次带di枚ci硬币&#xff0c;买s i的价值的东西。请问每次有多少种付款方法。 In…

ios 启用 证书_如何在iOS 10中启用就寝提醒,轻柔的唤醒和睡眠跟踪

ios 启用 证书If you have trouble regularly getting a full night’s sleep, the new Bedtime feature in iOS 10 might just help. Set a wake up time and how many hours of sleep you need, and iOS offers bedtime reminders, more gentle alarms, and basic sleep trac…

struts OGNL表达式

OGNLContext对象有两部分构成 一部分是ROOT&#xff1a;可以放置任何对象作为ROOT 另外一部分Context&#xff1a;必须是Map形式&#xff08;键值对&#xff09; OGNL表达式操作 package cn.future.a_ognl;import java.util.HashMap; import java.util.Map;import ognl.Ognl; i…

纤程(FIBER)

Indy 10 还包含对纤程的支持。纤程是什么&#xff1f;简单来说&#xff0c;它也是 一个“线程”&#xff0c;但是它是由代码控制的&#xff0c;而不是由操作系统控制的。实际上&#xff0c;可以认为线程 是一个高级纤程。纤程和 Unix 用户线程(Unix user threads)很相似。 线程…

制作一个用户头像选择器仿 WeGame

制作一个用户头像选择器仿 WeGameCropAvatar作者&#xff1a;WPFDevelopersOrg - 驚鏵原文链接&#xff1a;https://github.com/WPFDevelopersOrg/WPFDevelopers框架使用.NET40&#xff1b;Visual Studio 2019;制作一个用户头像选择Canvas为父控件所实现&#xff0c;展示图片使…