Igor Meszaros
Igor Meszaros

Reputation: 2127

json enum default value c#

I'm trying to serialize a large struct with loads of enums, and when a property in the struct is not set, I would like to get the first enum string value to be serialized in json instead im getting 0 as a default value.

public enum YesNoUnknown
{
    [EnumName(Name = "unknown")]
    Unknown,

    [EnumName(Name = "yes")]
    Yes,

    [EnumName(Name = "no")]
    No
}

[JsonProperty(PropertyName = "property1", ItemConverterType = typeof(EnumAttributeConverter<YesNoUnknown>))]
public YesNoUnknown Property1 { get; set; }

I want the default result to be: property1: "unknown" instead of: property1: 0

Thanks in advance!

Upvotes: 0

Views: 2251

Answers (1)

Igor Meszaros
Igor Meszaros

Reputation: 2127

Turns out the problem was that i should have used the Json EnumString attribute instead of using my custom attribute. So these are the changes I made to make it work:

public enum YesNoUnknown
{
    [EnumString("unknown")]
    Unknown,

    [EnumString("yes")]
    Yes,

    [EnumString("no")]
    No
}

    [JsonProperty(PropertyName = "property1")]
    [JsonConverter(typeof(EnumAttributeConverter<YesNoUnknown>))]
    public YesNoUnknown Property1 { get; set; }

Upvotes: 1

Related Questions