[英]Custom JSON serializer
我有课
partial class Customer
{
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public string Address{ get; set; }
[JsonProperty]
public string CardInfo { get; set; }
public int CustomerId { get; set; }
}
当我将此序列化时,customerId不存在。 这就是我希望它起作用的方式。 我有一个单独的方法,我需要将customerId发送回去。 所以我应该使用自定义序列化程序吗? 有没有一种方法可以使用相同的类来实现。
您可以使用JSON.Net的条件序列化功能:
partial class Customer
{
// Ignoring the property since it's only used to indicate if we should serialize
// CustomerId or not
[JsonIgnore]
public bool IncludeCustomerId {get;set;}
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public string Address{ get; set; }
[JsonProperty]
public string CardInfo { get; set; }
public int CustomerId { get; set; }
public bool ShouldSerializeCustomerId()
{
return IncludeCustomerId;
}
}
现在,如果将IncludeCustomerId
设置为true
则Json.Net将仅序列化CustomerId
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.