using xApi.Models; using System.Text.Json; using System.Text.Json.Serialization; namespace xApi.Extensions { public static class ModelExtensions { // #region Common ... /// /// Parse Json String to Specified Type of Object ... /// /// /// /// /// /// public static T? ParseJSON( this string json, JsonSerializerOptions? options = null ) { // if (string.IsNullOrWhiteSpace(json)) { return default; } // // Normalize ... options = GetDefaultJsonSerializerOptions(options); // try { // return JsonSerializer .Deserialize(json, options); } catch (JsonException ex) { throw new InvalidOperationException($"Failed to deserialize JSON to {typeof(T).Name}", ex); } } /// /// Convert to Json String ... /// /// /// /// /// public static string? ToJSON( this object? obj, JsonSerializerOptions? options = null ) { // if (obj is null) { return null; } // options = GetDefaultJsonSerializerOptions(options); try { // return JsonSerializer .Serialize(obj, options); } catch (NotSupportedException ex) { throw new InvalidOperationException($"Failed to serialize object of type {obj.GetType().Name}", ex); } } /// /// Convert to Pretty Json String ... /// /// /// /// public static string? ToPrettyJSON( this object? obj, JsonSerializerOptions? options = null ) { // if (obj is null) { return null; } // options = GetDefaultJsonSerializerOptions(options); options.WriteIndented = true; return JsonSerializer.Serialize(obj, options); } #endregion /// /// Validate Configuration Model ... /// /// /// public static bool IsValid(this ApiConfiguration? configuration) { // var result = configuration != null && !string.IsNullOrWhiteSpace(configuration.Name) && !string.IsNullOrWhiteSpace(configuration.Version) && !string.IsNullOrWhiteSpace(configuration.Description); // return result; } /// /// Validate Configuration Model ... /// /// /// public static bool IsValid(this AzureServiceConfiguration? configuration) { // var result = configuration != null && !string.IsNullOrWhiteSpace(configuration.Pat) && !string.IsNullOrWhiteSpace(configuration.BaseUrl); // return result; } // #region Private ... /// /// Retrieve Default JsonSerializerOptions ... /// /// /// private static JsonSerializerOptions GetDefaultJsonSerializerOptions( JsonSerializerOptions? options = null ) { // if (options is null) { options = new() { WriteIndented = false, PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, }; } // return options; } #endregion } }