简体   繁体   中英

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!

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM