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

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

There is a newer version: 7.7.0
Show 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 DateTimeNullableJsonConverter : JsonConverter
    {
        /// 
        /// The formats used to deserialize the date
        /// 
        public static string[] Formats { get; } = {
{{>DateTimeFormats}}
         };

        /// 
        /// Returns a DateTime from the Json object
        /// 
        /// 
        /// 
        /// 
        /// 
        public override DateTime? 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 (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result))
                    return result;

            return null;
        }

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy