json.net does not serialize properties from derived class(json.net 不序列化派生类的属性)
问题描述
我正在使用 JSON.NET 6.0.1.当我使用 SerializeObject
方法序列化派生类的对象时,它仅序列化基类的属性.以下是代码片段:
I'm using JSON.NET 6.0.1. When I use the SerializeObject
method to serialize an object of my derived class, it serializes properties from base class only. Here is the code snippet:
string v = JsonConvert.SerializeObject(
service,
Formatting.Indented,
new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
});
基类:
[DataContract]
public abstract partial class DataEntity : IDataEntity, INotifyPropertyChanging, INotifyPropertyChanged
{
...
}
派生类:
[Table(Name = "dbo.mytable")]
public sealed class mytable : DataEntity
{
...
}
我错过了什么吗?
推荐答案
是的,您缺少派生类的 [DataContract]
属性.您还需要将 [DataMember]
添加到您想要序列化的任何属性或字段(如果您尚未添加它们).Json.Net 在 5.0 版本 1 中进行了更改(4 月2013)这样 [DataContract]
属性不会被继承.
Yes, you are missing the [DataContract]
attribute on the derived class. You also need to add [DataMember]
to any properties or fields that you want serialized, if you haven't already added them. Json.Net was changed in version 5.0 release 1 (April 2013) such that the [DataContract]
attribute is not inherited.
请注意,如果您从您的类中删除所有 [DataContract]
和 [DataMemeber]
实例,Json.Net 的行为会有所不同:在在这种情况下,Json.Net 的默认行为是序列化所有公共属性,包括基类和派生类.
Note that if you remove all instances of [DataContract]
and [DataMemeber]
from your classes, Json.Net behaves differently: in that case, the default behavior is for Json.Net to serialize all public properties, both in the base and derived classes.
这篇关于json.net 不序列化派生类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:json.net 不序列化派生类的属性


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01