| | 1 | | using System.Text.Json; |
| | 2 | | using System.Text.Json.Serialization; |
| | 3 | |
|
| | 4 | | namespace Common.Core.Converters; |
| | 5 | |
|
| | 6 | | #region Nullable Integer |
| | 7 | |
|
| | 8 | | /// <summary>Converts a nullable integer (System.Int32) string to or from JSON.</summary> |
| | 9 | | public class JsonIntegerString : JsonConverter<int?> |
| | 10 | | { |
| | 11 | | /// <summary> |
| | 12 | | /// Gets a value that indicates whether null should be passed to the converter on serialization. |
| | 13 | | /// </summary> |
| 13 | 14 | | public override bool HandleNull => true; |
| | 15 | |
|
| | 16 | | /// <summary>Reads and converts the JSON to a nullable integer.</summary> |
| | 17 | | /// <param name="reader">The reader.</param> |
| | 18 | | /// <param name="typeToConvert">The type to convert.</param> |
| | 19 | | /// <param name="options">An object that specifies serialization options to use.</param> |
| | 20 | | /// <returns>The converted value or <see langword="null"/> if the value could not be converted.</returns> |
| | 21 | | public override int? Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options ) |
| 9 | 22 | | { |
| 9 | 23 | | switch( reader.TokenType ) |
| | 24 | | { |
| | 25 | | case JsonTokenType.Number: |
| 1 | 26 | | return reader.GetInt32(); |
| | 27 | |
|
| | 28 | | case JsonTokenType.String: |
| 3 | 29 | | string? value = reader.GetString(); |
| 3 | 30 | | value ??= string.Empty; |
| 5 | 31 | | if( StringConverter.TryParse( ref value, out int result ) ) { return result; } |
| 2 | 32 | | break; |
| | 33 | |
|
| | 34 | | default: |
| 5 | 35 | | break; |
| | 36 | | } |
| | 37 | |
|
| 7 | 38 | | return null; |
| 9 | 39 | | } |
| | 40 | |
|
| | 41 | | /// <summary>Writes a specified value as JSON.</summary> |
| | 42 | | /// <param name="writer">The writer to write to.</param> |
| | 43 | | /// <param name="value">The value to convert to JSON.</param> |
| | 44 | | /// <param name="options">An object that specifies serialization options to use.</param> |
| | 45 | | public override void Write( Utf8JsonWriter writer, int? value, JsonSerializerOptions options ) |
| 10 | 46 | | { |
| 10 | 47 | | if( value.HasValue ) |
| 3 | 48 | | { |
| 3 | 49 | | writer.WriteNumberValue( value.Value ); |
| 3 | 50 | | } |
| | 51 | | else |
| 7 | 52 | | { |
| 7 | 53 | | writer.WriteNullValue(); |
| 7 | 54 | | } |
| 10 | 55 | | } |
| | 56 | | } |
| | 57 | |
|
| | 58 | | #endregion |