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

时光总嘲笑我的痴心妄想 提交于 2019-12-30 13:42:28

问题


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?


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!