如何使用 C# 进行条件序列化 - NewtonSoft.Json
How to do Conditional Serialization using C# - NewtonSoft.Json
我正在使用 NewtonSoft.Json
进行 json 序列化
public class CommonBase
{
[JsonProperty(PropertyName = "u_customer_id")]
public long CustomerId { get; set; }
}
我想进行条件序列化,这样如果 CustomerId
值为 0,我想在 json 序列化期间为 CustomerId
设置空白值。由于 CommonBase
是基础 class,我无法将数据类型从 long
更改为 string
。
我怎样才能做到这一点?
您的问题标题中几乎已经有了答案。您要找的是 Conditional Property Serialization
您只需要添加这样命名的方法:ShouldSerialize + PropertyName
。在您的情况下,方法应如下所示:
public bool ShouldSerializeCustomerId()
{
return SomeCondition;
}
P.s。如果你正在创建基础 class,你可能想要抽象 class.
我已通过将 CustomerId 属性 更改为可为 null 来解决此问题。
public long? CustomerId { get; set; }
我正在使用 NewtonSoft.Json
进行 json 序列化public class CommonBase
{
[JsonProperty(PropertyName = "u_customer_id")]
public long CustomerId { get; set; }
}
我想进行条件序列化,这样如果 CustomerId
值为 0,我想在 json 序列化期间为 CustomerId
设置空白值。由于 CommonBase
是基础 class,我无法将数据类型从 long
更改为 string
。
我怎样才能做到这一点?
您的问题标题中几乎已经有了答案。您要找的是 Conditional Property Serialization
您只需要添加这样命名的方法:ShouldSerialize + PropertyName
。在您的情况下,方法应如下所示:
public bool ShouldSerializeCustomerId()
{
return SomeCondition;
}
P.s。如果你正在创建基础 class,你可能想要抽象 class.
我已通过将 CustomerId 属性 更改为可为 null 来解决此问题。
public long? CustomerId { get; set; }