4

dotnet C# 如何让 Json 序列化数组时序列化继承类的属性

 3 years ago
source link: https://lindexi.gitee.io/post/dotnet-C-%E5%A6%82%E4%BD%95%E8%AE%A9-Json-%E5%BA%8F%E5%88%97%E5%8C%96%E6%95%B0%E7%BB%84%E6%97%B6%E5%BA%8F%E5%88%97%E5%8C%96%E7%BB%A7%E6%89%BF%E7%B1%BB%E7%9A%84%E5%B1%9E%E6%80%A7.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
dotnet C# 如何让 Json 序列化数组时序列化继承类的属性

如果我使用的是具体的数组而我的数组是基类数组,而我传入子类的元素进行 json 序列化,可能发现 Json.NET 序列化没有包含子类元素的属性。如果要包含子类的属性或字段,可以在序列化的类数组定义为 object 数组的方式

我在用 WPF 写一个复杂的应用,我需要 ASP.NET Core 后台传输一个 AppData 类的数组,包含的属性如下

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

然后我有 Foo 类继承 Lindexi 类

public class Foo : Lindexi
{
	public string F1 { set; get; }
}

用下面代码序列化

        static void Main(string[] args)
        {
            Console.WriteLine(ToString(new Foo()
            {
                F1 = "林德熙是逗比"
            }));
        }

        static string ToString(Lindexi lindexi)
        {
            return JsonSerializer.Serialize(new [] { lindexi });
        }

运行可以看到输出

[{"Name":null}]

也就是 Foo 的属性被丢失了,在 .NET Core 3.0 可以使用 System.Text.Json 命名空间而不需要用 Newtonsoft.Json 库

此时解决方法是将数组定义为 object 数组

        static string ToString(Lindexi lindexi)
        {
            return JsonSerializer.Serialize(new object[] { lindexi });
        }

刚才定义的属性都是首字符大写的,转换为首字符小写的可以添加配置 PropertyNamingPolicy 请看下面

        static string ToString(Lindexi lindexi)
        {
            return JsonSerializer.Serialize(new object[] { lindexi }, new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });
        }

另外作为 json 上传到后台需要注意添加 “application/json” 请看代码

            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

win10 uwp 客户端如何发送类到 asp dotnet core 作为参数

如果你是被这个问题坑到的,同时一开始没有找到本文解决,请告诉我你之前搜的关键字,我去优化这个博客内容


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/dotnet-C-%E5%A6%82%E4%BD%95%E8%AE%A9-Json-%E5%BA%8F%E5%88%97%E5%8C%96%E6%95%B0%E7%BB%84%E6%97%B6%E5%BA%8F%E5%88%97%E5%8C%96%E7%BB%A7%E6%89%BF%E7%B1%BB%E7%9A%84%E5%B1%9E%E6%80%A7.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号

lindexi%2F201985113622445

欢迎进入 Eleven 老师组建的 .NET 社区

lindexi%2F20209121930471745.jpg

以上广告全是友情推广,无盈利


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK