我有一个班级,
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。可能我应该使用自定义序列化器?有没有办法使用同一个类实现这一目标。
答案 0 :(得分:0)
您可以使用JSON.Net的conditional serialization功能:
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;
}
}
现在,如果您将CustomerId
设置为IncludeCustomerId
,Json.Net将仅序列化true
。