- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在开发一个客户端/服务器数据驱动的应用程序,前端使用 caliburn.micro,后端使用 Asp.net WebApi 2。
public class Person
{
public int Id {get;set;}
public string FirstName{get;set;}
...
}
应用程序包含一个名为“Person”的类。 “人”对象被序列化 (JSON),并使用简单的 REST 协议(protocol)在客户端和服务器之间来回移动。该解决方案工作正常,没有任何问题。
问题:
为了实现 NotifyOfPropertyChanged(),我已经为“Person”设置了父类“PropertyChangedBase”。
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:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;
关于c# - 实现 PropertyChangedBase 时的 caliburn.micro 序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200648/
我正在开发一个客户端/服务器数据驱动的应用程序,前端使用 caliburn.micro,后端使用 Asp.net WebApi 2。 public class Person { public
我是一名优秀的程序员,十分优秀!