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; }
}
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; }
}
© 2025 juniyunapapa@gmail.com.