我正在開發(fā)一個客戶端/服務器數(shù)據(jù)驅(qū)動的應用程序,使用caliburn.micro作為前端,使用Asp.net WebApi 2作為后端.
public class Person
{
public int Id {get;set;}
public string FirstName{get;set;}
...
}
該應用程序包含一個名為“Person”的類. “Person”對象被序列化(JSON)并使用簡單的REST協(xié)議從客戶端到服務器來回移動.解決方案正常運行沒有任何問題.
問題:
我為“Person”設置了一個父類“PropertyChangedBase”,以實現(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值.
我猜序列化/反序列化存在問題. 這僅在實現(xiàn)PropertyChangedBase時發(fā)生.
任何人都可以幫我解決這個問題嗎? 解決方法: 您需要將[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.
(有關(guān)確認,請參閱Question about inheritance behavior of DataContract #872,確認Json.NET的此行為仍然符合預期.)
所以你需要添加這些屬性.
或者,如果您不希望在派生類中應用數(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
來源:http://www./content-1-198601.html
|