Search code examples
c#serializationjson.net

How to serialize list of enum using their string value


This is my enum type:

public enum AccessScope
{
    [JsonProperty("read_content")]
    ReadContent,

    [JsonProperty("write_content")]
    WriteContent,

    [JsonProperty("read_themes")]
    ReadThemes,

    [JsonProperty("write_themes")]
    WriteThemes
}  

I want to serialize this enum using the string values... when I try the following code, the numeric values are used for serialization:

[TestMethod]
public void Serialize_access_scopes()
{
    var requiredPermissions = new List<AccessScope>()
    {
        AccessScope.ReadContent,
        AccessScope.WriteContent,
    };

    var commaSeparatedPermissions = JsonConvert.SerializeObject(requiredPermissions);  

    commaSeparatedPermissions.Should().Be("read_content, write_content");
}

ialzie


Solution

  • You could use the StringEnumConverter provided by Json.Net rather than defining a custom converter, along with using the EnumMemberAttribute instead of JsonPropertyAttribute.

    For Example,

    [JsonConverter(typeof(StringEnumConverter))]
    public enum AccessScope
    {
        [EnumMember(Value="read_content")]
        ReadContent,
    
        [EnumMember(Value="write_content")]
        WriteContent,
    
        [EnumMember(Value="read_themes")]
        ReadThemes,
    
        [EnumMember(Value="write_themes")]
        WriteThemes
    } 
    

    Now you can deserialize as

    var requiredPermissions = new List<AccessScope>()
    {
        AccessScope.ReadContent,
        AccessScope.WriteContent,
    };
    
    var result = JsonConvert.SerializeObject(requiredPermissions);
    

    Output

    ["read_content","write_content"]