"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to serialize .NET enumeration into JSON strings with JavaScriptSerializer?

How to serialize .NET enumeration into JSON strings with JavaScriptSerializer?

Posted on 2025-04-12
Browse:647

How to Serialize a .NET Enum as a String in JSON using JavaScriptSerializer?

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:

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; }
}

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:

      [JsonConverter(typeof(StringEnumConverter))]
      public enum Gender { Male, Female }
  • With JsonSerializer: Add the converter to a specific JsonSerializer instance to affect only the enums serialized by that instance:

      var serializer = new JsonSerializer();
      serializer.Converters.Add(new StringEnumConverter());
      // ... use serializer to serialize your objects ...
  • With JsonConvert: Apply the converter directly during serialization:

      string json = JsonConvert.SerializeObject(myObject, new StringEnumConverter());

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3