Skip to content

Commit

Permalink
Added nullable int converter for System.Text.Json
Browse files Browse the repository at this point in the history
  • Loading branch information
JKorf committed Jun 25, 2024
1 parent 1ab85d4 commit 25567ea
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
40 changes: 40 additions & 0 deletions CryptoExchange.Net/Converters/SystemTextJson/IntConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace CryptoExchange.Net.Converters.SystemTextJson
{
/// <summary>
/// Int converter
/// </summary>
public class IntConverter : JsonConverter<int?>
{
/// <inheritdoc />
public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
return null;

if (reader.TokenType == JsonTokenType.String)
{
var value = reader.GetString();
if (string.IsNullOrEmpty(value))
return null;

return int.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture);
}

return reader.GetInt32();
}

/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
{
if (value == null)
writer.WriteNullValue();
else
writer.WriteNumberValue(value.Value);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public static class SerializerOptions
new EnumConverter(),
new BoolConverter(),
new DecimalConverter(),
new IntConverter()
}
};
}
Expand Down

0 comments on commit 25567ea

Please sign in to comment.