json.net不序列来源于类的属性 [英] json.net does not serialize properties from derived class

查看:138
本文介绍了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
                });



的基类:

base class:

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

派生类:

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

我缺少的东西吗?

推荐答案

是的,你缺少在在派生类[DataContract] 属性。您还需要添加 [数据成员] 来要系列化,如果您还没有加入他们的任何属性或字段。这是对的文档中的拼写 DataContractAttribute ,引如下(重点煤矿):

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. This is spelled out in the documentation for the DataContractAttribute class, as quoted below (emphasis mine):

注意

一个数据契约在其继承行为实际接口显著不同。接口由任何派生类型继承。 :当您应用DataContractAttribute基类,派生类型不会继承属性或行为。但是,如果派生类型具有数据合同,基类的数据成员被序列化。但是,必须应用DataMemberAttribute新成员在派生类中,使它们可序列化。

A data contract differs significantly from an actual interface in its inheritance behavior. Interfaces are inherited by any derived types. When you apply the DataContractAttribute to a base class, the derived types do not inherit the attribute or the behavior. However, if a derived type has a data contract, the data members of the base class are serialized. However, you must apply the DataMemberAttribute to new members in a derived class to make them serializable.

Json.Net变更为履行这一行为版本5.0版本1 (2013年4月)。

Json.Net was changed to honor this behavior in version 5.0 release 1 (April 2013).

请注意,如果你的删除的所有实例 [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不序列来源于类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆