Skip to content

Commit

Permalink
JsonStrIntEnumConverter
Browse files Browse the repository at this point in the history
  • Loading branch information
o.nadymov committed Sep 6, 2024
1 parent 099a765 commit b9a457b
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Spoleto.Common.Tests/JsonHelperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,5 +141,21 @@ public void EnumWithType()
Assert.That(fromJson.SystemType, Is.EqualTo(obj.SystemType));
});
}

[Test]
public void EnumWithStrInt()
{
// Arrange
var json = "{\"TestIntEnumAsStrInt\": \"200\"}";

// Act
var fromJson = JsonHelper.FromJson<TestClass>(json);

// Assert
Assert.Multiple(() =>
{
Assert.That(fromJson.TestIntEnumAsStrInt, Is.EqualTo(TestIntEnum.Two));
});
}
}
}
3 changes: 3 additions & 0 deletions src/Spoleto.Common.Tests/Objects/TestClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@ public class TestClass

[JsonConverter(typeof(JsonEnumIntValueConverter<TestEnumIntValue>))]
public TestEnumIntValue TestEnumIntValue2 { get; set; }

[JsonConverter(typeof(JsonStrIntEnumConverter<TestIntEnum>))]
public TestIntEnum TestIntEnumAsStrInt { get; set; }
}
}
35 changes: 35 additions & 0 deletions src/Spoleto.Common/JsonConverters/JsonStrIntEnumConverter.cs
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());
}
}
}

0 comments on commit b9a457b

Please # to comment.