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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…