All Downloads are FREE. Search and download functionalities are using the official Maven repository.

csharp.libraries.generichost.DateOnlyNullableJsonConverter.mustache Maven / Gradle / Ivy

The newest version!
{{>partial_header}}
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace {{packageName}}.{{clientPackage}}
{
    /// 
    /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339
    /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types
    /// 
    {{>visibility}} class DateOnlyNullableJsonConverter : JsonConverter
    {
        /// 
        /// The formats used to deserialize the date
        /// 
        public static string[] Formats { get; } = {
{{>DateFormats}}
        };

        /// 
        /// Returns a DateOnly from the Json object
        /// 
        /// 
        /// 
        /// 
        /// 
        public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
            if (reader.TokenType == JsonTokenType.Null)
                return null;

            string value = reader.GetString(){{nrt!}};

            foreach(string format in Formats)
                if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result))
                    return result;

            throw new NotSupportedException();
        }

        /// 
        /// Writes the DateOnly to the json writer
        /// 
        /// 
        /// 
        /// 
        public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options)
        {
            if (dateOnlyValue == null)
                writer.WriteNullValue();
            else
                writer.WriteStringValue(dateOnlyValue.Value.ToString("{{{dateFormat}}}", CultureInfo.InvariantCulture));
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy