简体   繁体   English

json.net 不会序列化派生类的属性

[英]json.net does not serialize properties from derived class

I'm using JSON.NET 6.0.1.我正在使用 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.当我使用SerializeObject方法序列化我的派生类的对象时,它仅序列化基类的属性。 Here is the code snippet:这是代码片段:

string v = JsonConvert.SerializeObject(
                service, 
                Formatting.Indented, 
                new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.All
                });

base class:基类:

[DataContract]
public abstract partial class DataEntity : IDataEntity, INotifyPropertyChanging, INotifyPropertyChanged
{
    ...
}

derived class:派生类:

[Table(Name = "dbo.mytable")]
public sealed class mytable : DataEntity
{
    ...
}

Am I missing something?我错过了什么吗?

Yes, you are missing the [DataContract] attribute on the derived class.是的,您缺少派生类的[DataContract]属性。 You also need to add [DataMember] to any properties or fields that you want serialized, if you haven't already added them.您还需要将[DataMember]添加到要序列化的任何属性或字段(如果尚未添加)。 Json.Net was changed in version 5.0 release 1 (April 2013) such that the [DataContract] attribute is not inherited. Json.Net 在5.0 版本 1 (2013 年 4 月)中进行了更改,因此[DataContract]属性不会被继承。

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.请注意,如果从类中删除[DataContract][DataMemeber]所有实例,Json.Net 的行为会有所不同:在这种情况下,Json.Net 的默认行为是序列化基类和派生类中的所有公共属性.

Adding the attribute [JsonObject(MemberSerialization.OptOut)] to your derived class will include all its public members to be serialized.将属性[JsonObject(MemberSerialization.OptOut)]到您的派生类将包括其所有要序列化的公共成员。

[Table(Name = "dbo.mytable")]
[JsonObject(MemberSerialization.OptOut)]
public sealed class mytable : DataEntity
{
    ...
}

Alternatively, if you only want certain properties of your derived class to be serialized you can add the attribute [JsonProperty] to each one (This would be equivalent of adding [DataMember] to each property along with [DataContract] on the class).或者,如果您只想序列化派生类的某些属性,您可以将属性[JsonProperty]添加到每个属性(这相当于将[DataMember]与类上的[DataContract]一起添加到每个属性)。

JsonConvert.SerializeObject was only return {} for me. JsonConvert.SerializeObject 对我来说只是返回 {}。 I found that I needed to add a new constructor to the class before it serialized properly.我发现我需要在类正确序列化之前向类添加一个新的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM