Search code examples
c#.netserializationjson.netjsonserializer

How to do Conditional Serialization using C# - NewtonSoft.Json


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?


Solution

  • I have solved this issue by changing CustomerId property as nullable.

       public long? CustomerId { get; set; }