[C#] Convert enum type to string during JSON Serialization
발행일: Jan, 2025
조회수: 0
단어수: 103
Table of Contents
Serializing Enums as Strings in JSON
When serializing JSON, data is typically stored as a text file or in a database. However, enum values are often stored as numbers, which reduces readability when inspecting JSON strings. To improve readability, it's common to store enum values as strings. This can be achieved by applying a specific attribute to the enum variable, as shown below:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public enum CompanyType {
Apple,
Samsung,
}
public class Company
{
[JsonConverter(typeof(StringEnumConverter))]
public CompanyType CompanyType { get; set; }
}
Serializing Enum Lists in JSON
If the member variable is an array or list, you can specify the attribute differently, as demonstrated in the following example:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public enum CompanyType {
Apple,
Samsung,
}
public class Company
{
[JsonConverter(typeof(StringEnumConverter))]
public CompanyType CompanyType { get; set; }
[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public List<CompanyType> CompanyTypes { get; set; }
}