| | 1 | | using System.Text.Json; |
| | 2 | | using System.Text.Json.Serialization; |
| | 3 | |
|
| | 4 | | namespace Common.Core.Converters; |
| | 5 | |
|
| | 6 | | #region Nullable DateOnly |
| | 7 | |
|
| | 8 | | /// <summary>Converts a nullable DateOnly string to or from JSON.</summary> |
| | 9 | | public class JsonDateOnlyString : JsonConverter<DateOnly?> |
| | 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 DateOnly.</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 DateOnly? Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options ) |
| 9 | 22 | | { |
| 9 | 23 | | switch( reader.TokenType ) |
| | 24 | | { |
| | 25 | | case JsonTokenType.String: |
| 2 | 26 | | string? value = reader.GetString(); |
| 2 | 27 | | value ??= string.Empty; |
| 4 | 28 | | if( StringConverter.TryParse( ref value, out DateOnly result ) ) { return result; } |
| 1 | 29 | | break; |
| | 30 | |
|
| | 31 | | default: |
| 7 | 32 | | break; |
| | 33 | | } |
| | 34 | |
|
| 8 | 35 | | return null; |
| 9 | 36 | | } |
| | 37 | |
|
| | 38 | | /// <summary>Writes a specified value as JSON.</summary> |
| | 39 | | /// <param name="writer">The writer to write to.</param> |
| | 40 | | /// <param name="value">The value to convert to JSON.</param> |
| | 41 | | /// <param name="options">An object that specifies serialization options to use.</param> |
| | 42 | | public override void Write( Utf8JsonWriter writer, DateOnly? value, JsonSerializerOptions options ) |
| 10 | 43 | | { |
| 10 | 44 | | if( value.HasValue ) |
| 2 | 45 | | { |
| 2 | 46 | | writer.WriteStringValue( value.Value.ToString() ); |
| 2 | 47 | | } |
| | 48 | | else |
| 8 | 49 | | { |
| 8 | 50 | | writer.WriteNullValue(); |
| 8 | 51 | | } |
| 10 | 52 | | } |
| | 53 | | } |
| | 54 | |
|
| | 55 | | #endregion |