Skip to content

Commit

Permalink
Merge pull request #19132 from abpframework/AbpStringToEnumConverter
Browse files Browse the repository at this point in the history
Pass `JsonSerializerOptions` when serializing the `enum`.
  • Loading branch information
realLiangshiwei committed Feb 26, 2024
2 parents 890b12b + 6c9e709 commit 5a9f0e6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ public class AbpStringToEnumConverter<T> : JsonConverter<T>

private JsonSerializerOptions? _readJsonSerializerOptions;

private JsonSerializerOptions? _writeJsonSerializerOptions;

public AbpStringToEnumConverter()
: this(namingPolicy: null, allowIntegerValues: true)
{
Expand Down Expand Up @@ -39,7 +41,11 @@ public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerial

public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value);
_writeJsonSerializerOptions ??= JsonSerializerOptionsHelper.Create(options, x =>
x == this ||
x.GetType() == typeof(AbpStringToEnumFactory));

JsonSerializer.Serialize(writer, value, _writeJsonSerializerOptions);
}

public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Shouldly;
using Volo.Abp.Json.SystemTextJson.JsonConverters;
using Xunit;
Expand Down Expand Up @@ -53,10 +54,26 @@ public void Test_Write()
var testClassJson = JsonSerializer.Serialize(new TestClass()
{
Day = DayOfWeek.Monday
});
}, options);

testClassJson.ShouldBe("{\"Day\":1}");

options = new JsonSerializerOptions()
{
Converters =
{
new AbpStringToEnumFactory(),
new JsonStringEnumConverter()
}
};

testClassJson = JsonSerializer.Serialize(new TestClass()
{
Day = DayOfWeek.Monday
}, options);

testClassJson.ShouldBe("{\"Day\":\"Monday\"}");

testClassJson = JsonSerializer.Serialize(new Dictionary<DayOfWeek, string>
{
{DayOfWeek.Monday, "Mo"}
Expand Down

0 comments on commit 5a9f0e6

Please sign in to comment.