打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
实现PropertyChangedBase时c# – caliburn.micro序列化问题

我正在开发一个客户端/服务器数据驱动的应用程序,使用caliburn.micro作为前端,使用Asp.net WebApi 2作为后端.

public class Person{    public int Id {get;set;}    public string FirstName{get;set;}    ...}

该应用程序包含一个名为“Person”的类. “Person”对象被序列化(JSON)并使用简单的REST协议从客户端到服务器来回移动.解决方案正常运行没有任何问题.

问题:

我为“Person”设置了一个父类“PropertyChangedBase”,以实现NotifyOfPropertyChanged().

public class Person : PropertyChangedBase{    public int Id {get;set;}    private string _firstName;    public string FirstName    {        get { return _firstName; }        set        {            _firstName = value;            NotifyOfPropertyChange(() => FirstName);        }    }    ...}

但是这次“Person”类的属性在接收端有NULL值.

我猜序列化/反序列化存在问题.
这仅在实现PropertyChangedBase时发生.

任何人都可以帮我解决这个问题吗?

解决方法:

您需要将[DataContract]属性添加到Person类,并将[DataMember]属性添加到要序列化的每个属性和字段:

[DataContract]public class Person : PropertyChangedBase{    [DataMember]    public int Id { get; set; }    private string _firstName;    [DataMember]    public string FirstName { get; set; }}

您需要这样做,因为caliburn.micro基类PropertyChangedBase具有[DataContract]属性:

namespace Caliburn.Micro {    [DataContract]    public class PropertyChangedBase : INotifyPropertyChangedEx    {    }}

但为什么这有必要呢?理论上,应用于基类的DataContractAttribute的存在不应该影响派生的Person类,因为DataContractAttribute sets AttributeUsageAttribute.Inherited = false

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Struct|AttributeTargets.Enum, Inherited = false, AllowMultiple = false)]public sealed class DataContractAttribute : Attribute

但是,HttpClientExtensions.PostAsJsonAsync使用默认实例JsonMediaTypeFormatter,其中by default uses the Json.NET library to perform serialization.和Json.NET不遵守DataContractAttribute的Inherited = false属性,如here所述.

[Json.NET] detects the DataContractAttribute on the base class and assumes opt-in serialization.

(有关确认,请参阅Question about inheritance behavior of DataContract #872,确认Json.NET的此行为仍然符合预期.)

所以你需要添加这些属性.

或者,如果您不希望在派生类中应用数据协定属性,则可以按照此处的说明切换到DataContractJsonSerializer:JSON and XML Serialization in ASP.NET Web API

If you prefer, you can configure the JsonMediaTypeFormatter class to use the DataContractJsonSerializer instead of Json.NET. To do so, set the UseDataContractJsonSerializer property to true:

06003

来源:http://www.icode9.com/content-1-198601.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C# 技巧(3) C# 操作 JSON
C# WPF框架Caliburn.Micro快速搭建
怎样对带有不可序列化属性的Java对象进行序列化
Jackson常用注解介绍
JSON Views 高级用法
从MVC到前后端分离
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服