-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
o.nadymov
committed
Sep 6, 2024
1 parent
099a765
commit b9a457b
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
src/Spoleto.Common/JsonConverters/JsonStrIntEnumConverter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using System; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace Spoleto.Common.JsonConverters | ||
{ | ||
/// <summary> | ||
/// In can parse from string and from numbers but write as string only. | ||
/// </summary> | ||
/// <typeparam name="T"></typeparam> | ||
public class JsonStrIntEnumConverter<T> : JsonConverter<T> where T : struct, Enum | ||
{ | ||
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
if (reader.TokenType == JsonTokenType.String) | ||
{ | ||
var strInt = reader.GetString(); | ||
if (int.TryParse(strInt, out var result)) | ||
return (T)(object)result; | ||
} | ||
|
||
if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out var intValue)) | ||
{ | ||
return (T)(object)intValue; | ||
} | ||
|
||
throw new JsonException($"Unable to convert to Enum \"{typeToConvert}\"."); | ||
} | ||
|
||
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) | ||
{ | ||
writer.WriteStringValue(value.ToString()); | ||
} | ||
} | ||
} |