Home > front end >  C# JsonIgnore to basic class
C# JsonIgnore to basic class

Time:01-19

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

CodePudding user response:

You could define a custom contract resolver to ignore the properties. For example,

public class ShouldSerializeContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (property.DeclaringType == typeof(ViewModelBase) && property.PropertyName == "IsInDesignMode")
        {
            property.ShouldSerialize = x=> false;
        }

        return property;
    }
}

Now you could serialize your data by specifying the contract resolver.

var result = JsonConvert.SerializeObject(
    data,
    Formatting.Indented,
    new JsonSerializerSettings { ContractResolver = new ShouldSerializeContractResolver() }
);

CodePudding user response:

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

CodePudding user response:

Anu Viswan gave (IMHO) a very good solution.

Alternately, you could use the attribute [JsonObject(MemberSerialization.OptIn)] on top of your class(es) to serialize, which will give you the ability to choose clearly which fields you want to serialize.

But it has a drawback : you will have to put the [JsonProperty] on every property you want in JSON. Very handful for some cases, but it can be tedious if you have a lot of classes to serialize.

You can choose which solution looks to be the best for you :)

  •  Tags:  
  • Related