問題描述
我正在使用 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 不序列化派生類的屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!