Custom Json.NET converter should not serialize a property

前端 未结 1 1988
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 03:44

I have written a Json.NET converter which outputs all the set flags as an array.

enum SampleEnum
{
    None = 0,
    Value         


        
相关标签:
1条回答
  • 2021-01-24 04:41

    A custom JsonConverter cannot prevent its value from being serialized, because the property name referring to it will already have been written out by the time the converter is invoked. In Json.NET's architecture it is the responsibility of the containing type to decide which of its properties to serialize; the value converter then decides how to serialize the value being written.

    As an alternative, the setting DefaultValueHandling.Ignore can be used to skip serialization of enum members even when a converter is applied. Since SampleEnum.None has the value 0, it is the default value for your flags enumeration. Members with this value will this be skipped when the setting is enabled whether or not a converter is applied.

    You can enable DefaultValueHandling by applying it via JsonPropertyAttribute.DefaultValueHandling:

    public class SerializedClass
    {
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        [JsonConverter(typeof(ArrayEnumConverter))]
        public SampleEnum SampleEnum { get; set; }
    }
    

    Sample fiddle here.

    Incidentally, you should consider marking your SampleEnum with the [Flags] attribute:

    [Flags]
    public enum SampleEnum
    {
        None = 0,
        ValueA = 2,
        ValueB = 4
    }
    

    This is the recommended best practice for flag enums:

    Designing Flag Enums

    √ DO apply the System.FlagsAttribute to flag enums. Do not apply this attribute to simple enums.

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