Browse Source

Pass `JsonSerializerOptions` when serializing the `enum`.

pull/19132/head
maliming 3 years ago
parent
commit
6c9e70990b
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 8
      framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpStringToEnumConverter.cs
  2. 19
      framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpStringToEnum_Tests.cs

8
framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpStringToEnumConverter.cs

@ -11,6 +11,8 @@ public class AbpStringToEnumConverter<T> : JsonConverter<T>
private JsonSerializerOptions? _readJsonSerializerOptions; private JsonSerializerOptions? _readJsonSerializerOptions;
private JsonSerializerOptions? _writeJsonSerializerOptions;
public AbpStringToEnumConverter() public AbpStringToEnumConverter()
: this(namingPolicy: null, allowIntegerValues: true) : 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) 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) public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

19
framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpStringToEnum_Tests.cs

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization;
using Shouldly; using Shouldly;
using Volo.Abp.Json.SystemTextJson.JsonConverters; using Volo.Abp.Json.SystemTextJson.JsonConverters;
using Xunit; using Xunit;
@ -53,10 +54,26 @@ public class AbpStringToEnum_Tests
var testClassJson = JsonSerializer.Serialize(new TestClass() var testClassJson = JsonSerializer.Serialize(new TestClass()
{ {
Day = DayOfWeek.Monday Day = DayOfWeek.Monday
}); }, options);
testClassJson.ShouldBe("{\"Day\":1}"); 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> testClassJson = JsonSerializer.Serialize(new Dictionary<DayOfWeek, string>
{ {
{DayOfWeek.Monday, "Mo"} {DayOfWeek.Monday, "Mo"}

Loading…
Cancel
Save