Search code examples
c#json-serialization

Making property [NonSerialized] for a value


I am trying to figure out how can i make a property [NonSerialized] for a value

Check this out :

using System;
using System.Text.Json;
 
class Test
{
    public static bool GoingToBeSerialized = false;
 
 
    public int PaymentForTheDay { get; set; }
    public int NumberOfDays { get; set; }
 
    // i want to disable it if GoingToBeSerialized is true
    [System.Text.Json.Serialization.JsonIgnore] 
    public int TotalPayment;
 
    public  bool ShouldSerializeTotalPayment() => GoingToBeSerialized;
}

Thanks.


Solution

  • Note that [Serializable] and [NonSerialized] (in the original question, now removed in the edit) do nothing with most serializers - they only apply to BinaryFormatter, which you aren't using.

    There's a very good chance that simply using:

    public int TotalPayment {get;set;}
    public bool ShouldSerializeTotalPayment() => GoingToBeSerialized;
    

    will do what you want; with the recent addition of your pastebin that shows you're using Json.NET, this should indeed work - conditional serialization is a Json.NET feature using the standard pattern. Note also that I made TotalPayment a property, and removed the [JsonIgnore].