I am doing json serialization using NewtonSoft.Json
public class CommonBase
{
[JsonProperty(PropertyName = "u_customer_id")]
public long CustomerId { get; set; }
}
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
.
How can I achieve this?
You almost have the answer in your question title. What you are looking for is Conditional Property Serialization
You just need to add method named like this: ShouldSerialize + PropertyName
. In your case method should look like:
public bool ShouldSerializeCustomerId()
{
return SomeCondition;
}
P.s. if you are creating base class, you probably want to have abstract class.
I have solved this issue by changing CustomerId property as nullable.
public long? CustomerId { get; set; }
来源:https://stackoverflow.com/questions/42781725/how-to-do-conditional-serialization-using-c-sharp-newtonsoft-json