Search code examples
c#jsonmvvm-light

C# JsonIgnore to basic class


I have class

public class SettingsExpires : ViewModelBase
{
    private int? frequency;
    [JsonProperty("frequency")]
    public int? Frequency
    {
        get => frequency;
        set => this.Set(ref frequency, value);
    }
}

Where ViewModelBase is abstract class from GalaSoft.MvvmLight My problem start when I try serialize my class to json and get this:

{{  "frequency": null, "IsInDesignMode": false}}

I get IsInDesignMode from basic class ViewModelBase

public bool IsInDesignMode { get; }

How can I ignore this property from base class ? I tried something like this:

public class SettingsExpires : ViewModelBase
{
    private int? frequency;
    [JsonProperty("frequency")]
    public int? Frequency
    {
        get => frequency;
        set => this.Set(ref frequency, value);
    }
    [JsonIgnore]
    public new bool IsInDesignMode { get; }
}

or this:

public class SettingsExpires : ViewModelBase
{
    private int? frequency;
    [JsonProperty("frequency")]
    public int? Frequency
    {
        get => frequency;
        set => this.Set(ref frequency, value);
    }
    [JsonIgnore]
    public bool IsInDesignMode { get; }
}

but it doesn't work


Solution

  • By decorating your derived class (SettingsExpires) with the following attribute:

    [JsonObject(MemberSerialization.OptIn)]
    

    you are basically instructing the serializer to include only those properties which are explicitly annotated with JsonProperty. Everything else will be ignored.

    Reference