如何使用C#执行条件序列化-NewtonSoft.Json
问题描述:
我正在使用NewtonSoft.Json做json序列化
I am doing json serialization using NewtonSoft.Json
public class CommonBase
{
[JsonProperty(PropertyName = "u_customer_id")]
public long CustomerId { get; set; }
}
我想进行条件序列化,以便如果CustomerId
的值为0,我想在json序列化期间为CustomerId
设置一个空白值.由于CommonBase
是基类,因此我无法将数据类型从long
更改为string
.
I want to do a conditional serialization so that if CustomerId
value is 0, I want to set a blank value for CustomerId
during json serialization. Since CommonBase
is a base class and I am not able to change data type from long
to string
.
我该如何实现?
答
我已通过将CustomerId属性更改为可为空来解决此问题.
I have solved this issue by changing CustomerId property as nullable.
public long? CustomerId { get; set; }