😜

쭈나아빠 블로그

JUNA
STUDIO

[C#] Convert enum type to string during JSON Serialization

발행일: Jan, 2025
조회수: 5
단어수: 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; }
}
Tags: #C##ENUM#enumToString#JSON#Serialization#열거형을 문자열로 직렬화#직렬화
JUNA BLOG VISITORS
Today
7
 (
updown
-7
)
Total
657
 (
updown
+7
)

© 2025 juniyunapapa@gmail.com.