我正在开发一个客户端/服务器数据驱动的应用程序,使用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:
来源:http://www.icode9.com/content-1-198601.htmlIf 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
联系客服