Chris
Chris

Reputation: 345

How to serialize enum to null value using JSON.net

I'm working with a 3rd party REST API in which one of the fields (type string) has a known set of values that I've modeled as an enum in my code. The StringEnumConverter from JSON.NET correctly serializes all but one of these values as described by the [EnumMemberAttribute] annotation. For this field in particular, the REST API translates a null value to mean "System Default" in the 3rd party system; however, when JSON.NET serializes this it uses the member name instead of the value described in the annotation. I know I could write a custom converter to handle this , but my question is if there is a way to get this to work without one since it's only the null value that doesn't serialize correctly?

The enum I have defined in my code:

[JsonConverter(typeof(StringEnumConverter))]
public enum InitialScanLevel
{
    [EnumMember(Value = null)]
    SystemDefault,

    [EnumMember(Value = "0")]
    ModelDeviceOnly,

    [EnumMember(Value = "1")]
    InitialAppPopulation,

    [EnumMember(Value = "2")]
    DiscoverSslCerts,

    [EnumMember(Value = "3")]
    DiscoverOpenPorts,

    [EnumMember(Value = "4")]
    AdvancedPortDiscovery,

    [EnumMember(Value = "5")]
    DeepDiscovery
}

For InitialScanLevel.SystemDefault the resulting JSON is (not what the 3rd party API expects)

{
    other fields...,
    "initialScanLevel":"SystemDefault",
    other fields...
}

but should be

{
    other fields...,
    "initialScanLevel":null,
    other fields...
}

For InitialScanLevel.DeepDiscovery the resulting JSON is (this is what the 3rd party API expects)

{
    other fields...,
    "initialScanLevel":"5",
    other fields...
}

Upvotes: 6

Views: 8389

Answers (1)

L.B
L.B

Reputation: 116168

I think the easies way to do it is using a custom StringEnumConverter

public class MyStringEnumConverter : Newtonsoft.Json.Converters.StringEnumConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value.Equals(InitialScanLevel.SystemDefault)) value = null;
        base.WriteJson(writer, value, serializer);
    }
}

[JsonConverter(typeof(MyStringEnumConverter))]
public enum InitialScanLevel
{
 .....
}

Upvotes: 10

Related Questions