我正在開發(fā)一個(gè)客戶端/服務(wù)器數(shù)據(jù)驅(qū)動(dòng)的應(yīng)用程序,使用caliburn.micro作為前端,使用Asp.net WebApi 2作為后端.
public class Person
{
public int Id {get;set;}
public string FirstName{get;set;}
...
}
該應(yīng)用程序包含一個(gè)名為“Person”的類. “Person”對(duì)象被序列化(JSON)并使用簡(jiǎn)單的REST協(xié)議從客戶端到服務(wù)器來(lái)回移動(dòng).解決方案正常運(yùn)行沒有任何問題.
問題:
我為“Person”設(shè)置了一個(gè)父類“PropertyChangedBase”,以實(shí)現(xiàn)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值.
我猜序列化/反序列化存在問題. 這僅在實(shí)現(xiàn)PropertyChangedBase時(shí)發(fā)生.
任何人都可以幫我解決這個(gè)問題嗎? 解決方法: 您需要將[DataContract] 屬性添加到Person類,并將[DataMember] 屬性添加到要序列化的每個(gè)屬性和字段:
[DataContract]
public class Person : PropertyChangedBase
{
[DataMember]
public int Id { get; set; }
private string _firstName;
[DataMember]
public string FirstName { get; set; }
}
您需要這樣做,因?yàn)?a rel="nofollow noreferrer">caliburn.micro基類PropertyChangedBase 具有[DataContract]屬性:
namespace Caliburn.Micro {
[DataContract]
public class PropertyChangedBase : INotifyPropertyChangedEx
{
}
}
但為什么這有必要呢?理論上,應(yīng)用于基類的DataContractAttribute 的存在不應(yīng)該影響派生的Person類,因?yàn)?a rel="nofollow noreferrer">DataContractAttribute sets AttributeUsageAttribute.Inherited = false :
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Struct|AttributeTargets.Enum, Inherited = false,
AllowMultiple = false)]
public sealed class DataContractAttribute : Attribute
但是,HttpClientExtensions.PostAsJsonAsync 使用默認(rèn)實(shí)例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.
(有關(guān)確認(rèn),請(qǐng)參閱Question about inheritance behavior of DataContract #872,確認(rèn)Json.NET的此行為仍然符合預(yù)期.)
所以你需要添加這些屬性.
或者,如果您不希望在派生類中應(yīng)用數(shù)據(jù)協(xié)定屬性,則可以按照此處的說明切換到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
來(lái)源:http://www./content-1-198601.html
|