Serializing .NET Enums as Strings in JSON with JavaScriptSerializer
The standard .NET JavaScriptSerializer
often outputs enums as their integer values within JSON. To serialize them as strings representing their names, several methods exist.
Method 1: Leveraging JSON.NET's StringEnumConverter
The most straightforward and recommended approach utilizes JSON.NET's powerful StringEnumConverter
. This converter can be applied at either the enum definition level or the property level:
<code class="language-csharp">using Newtonsoft.Json; using Newtonsoft.Json.Converters; [JsonConverter(typeof(StringEnumConverter))] public enum Gender { Male, Female } public class Person { public int Age { get; set; } [JsonConverter(typeof(StringEnumConverter))] // Or apply at property level public Gender Gender { get; set; } }</code>
This ensures the Gender
property serializes as a string ("Male" or "Female") in the resulting JSON.
Method 2: Global Configuration Options
For broader application, configure the StringEnumConverter
globally:
At the Enum Level: Apply the converter to the enum definition itself for consistent string serialization across all uses of that enum:
<code class="language-csharp"> [JsonConverter(typeof(StringEnumConverter))] public enum Gender { Male, Female }</code>
With JsonSerializer
: Add the converter to a specific JsonSerializer
instance to affect only the enums serialized by that instance:
<code class="language-csharp"> var serializer = new JsonSerializer(); serializer.Converters.Add(new StringEnumConverter()); // ... use serializer to serialize your objects ...</code>
With JsonConvert
: Apply the converter directly during serialization:
<code class="language-csharp"> string json = JsonConvert.SerializeObject(myObject, new StringEnumConverter());</code>
Customization of StringEnumConverter
The StringEnumConverter
constructor offers further customization, allowing control over naming conventions and number handling. Refer to the JSON.NET documentation for detailed options.
The above is the detailed content of How to Serialize a .NET Enum as a String in JSON using JavaScriptSerializer?. For more information, please follow other related articles on the PHP Chinese website!