-
-
Notifications
You must be signed in to change notification settings - Fork 200
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added nullable int converter for System.Text.Json
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
CryptoExchange.Net/Converters/SystemTextJson/IntConverter.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,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); | ||
} | ||
} | ||
} |
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