Browse Source
Pass `JsonSerializerOptions` when serializing the `enum`.
pull/19132/head
maliming
2 years ago
No known key found for this signature in database
GPG Key ID: A646B9CB645ECEA4
2 changed files with
25 additions and
2 deletions
-
framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpStringToEnumConverter.cs
-
framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpStringToEnum_Tests.cs
|
|
|
@ -11,6 +11,8 @@ public class AbpStringToEnumConverter<T> : JsonConverter<T> |
|
|
|
|
|
|
|
private JsonSerializerOptions? _readJsonSerializerOptions; |
|
|
|
|
|
|
|
private JsonSerializerOptions? _writeJsonSerializerOptions; |
|
|
|
|
|
|
|
public AbpStringToEnumConverter() |
|
|
|
: this(namingPolicy: null, allowIntegerValues: true) |
|
|
|
{ |
|
|
|
@ -39,7 +41,11 @@ public class AbpStringToEnumConverter<T> : JsonConverter<T> |
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
@ -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; |
|
|
|
@ -53,10 +54,26 @@ public class AbpStringToEnum_Tests |
|
|
|
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"} |
|
|
|
|