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

后端 未结 2 779
盖世英雄少女心
盖世英雄少女心 2021-01-16 20:33

I am doing json serialization using NewtonSoft.Json

public class CommonBase
{
    [JsonProperty(PropertyName = \"u_customer_id\")]
    public long CustomerId         


        
相关标签:
2条回答
  • 2021-01-16 21:24

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

       public long? CustomerId { get; set; }
    
    0 讨论(0)
  • 2021-01-16 21:36

    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.

    0 讨论(0)
提交回复
热议问题