Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

c# - Custom Json.NET converter should not serialize a property

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

enum SampleEnum
{
    None = 0,
    ValueA = 2,
    ValueB = 4
}

SampleEnum flags = SampleEnum.ValueA | SampleEnum.ValueB;
// JSON: ["ValueA", "ValueB"]

Now in case flags is SampleEnum.None, the property should not be serialized. Therefore I just don't write anything to the JsonWriter. Here is the code of the WriteJson method of the converter.

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    if (value is SampleEnum enumValue)
    {
        IEnumerable<SampleEnum> setFlags = GetSetFlags<SampleEnum>(enumValue);              

        IEnumerable<string> flagNames = setFlags
            .Where(flag => flag != SampleEnum.None) // Filter out 'None'
            .Select(flag => flag.ToString());

        if (flagNames.Any())
        {
            JArray jArray = JArray.FromObject(flagNames, serializer);
            jArray.WriteTo(writer);
        }
        // Else omit this property
    }
}

However, if I have a property of type SampleEnum in my class and its value is SampleEnum.None, the property is serialized and the JSON value is null.

class SerializedClass
{
    [JsonConverter(typeof(ArrayEnumConverter))]
    public SampleEnum EnumValue { get; set; }
}

SerializedClass obj = new SerializedClass
{
    EnumValue = SampleEnum.None
};
string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
});

The output is the following:

{
  "EnumValue": null
}

The output I wish to see:

{}

What can I do so that the property is omitted instead of being null?

P.S.: I've read about Conditional Property Serialization, but the ShouldSerialize methods are not suitable in my case and I haven't figured out yet how to use IContractResolver for my case.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...