using System.Text.Json; using System.Text.Json.Serialization;
var person = new Person(); var stringEnumConverter = new System.Text.Json.Serialization.JsonStringEnumConverter(); JsonSerializerOptions opts = new JsonSerializerOptions(); opts.Converters.Add(stringEnumConverter); var json = JsonSerializer.Serialize<Person>(person, opts);
也可以在属性或枚举类型上使用特性:
1 2 3 4 5 6 7
using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonStringEnumConverter))] public Gender Gender { get; set; }
using Newtonsoft.Json; using Newtonsoft.Json.Converters;
publicclassPerson { publicint Age { get; set; }
[JsonConverter(typeof(StringEnumConverter))] public Gender Gender { get; set; } }
publicenum Gender { Male, Female }
classProgram { staticvoidMain() { var person = new Person { Age = 30, Gender = Gender.Male }; string json = JsonConvert.SerializeObject(person); Console.WriteLine(json); } }
using System.Text.Json; using System.Text.Json.Serialization;
publicclassPerson { publicint Age { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter))] public Gender Gender { get; set; } }
publicenum Gender { Male, Female }
classProgram { staticvoidMain() { var person = new Person { Age = 30, Gender = Gender.Male }; var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } }; string json = JsonSerializer.Serialize(person, options); Console.WriteLine(json); } }
publicclassCustomStringEnumConverter : Newtonsoft.Json.Converters.StringEnumConverter { publicoverridevoidWriteJson(JsonWriter writer, objectvalue, JsonSerializer serializer) { Type type = value.GetType() as Type;
if (!type.IsEnum) thrownew InvalidOperationException("Only type Enum is supported"); foreach (var field in type.GetFields()) { if (field.Name == value.ToString()) { var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; writer.WriteValue(attribute != null ? attribute.Description : field.Name);