diff --git a/Lombiq.HelpfulLibraries.AspNetCore/Localization/LocalizedHtmlStringConverter.cs b/Lombiq.HelpfulLibraries.AspNetCore/Localization/LocalizedHtmlStringConverter.cs new file mode 100644 index 00000000..b55d57b7 --- /dev/null +++ b/Lombiq.HelpfulLibraries.AspNetCore/Localization/LocalizedHtmlStringConverter.cs @@ -0,0 +1,56 @@ +using Microsoft.AspNetCore.Mvc.Localization; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; + +namespace Lombiq.HelpfulLibraries.AspNetCore.Localization; + +public class LocalizedHtmlStringConverter : JsonConverter +{ + public override void WriteJson(JsonWriter writer, LocalizedHtmlString value, JsonSerializer serializer) + { + writer.WriteStartObject(); + + writer.WritePropertyName(nameof(LocalizedHtmlString.Name)); + writer.WriteValue(value.Name); + + writer.WritePropertyName(nameof(LocalizedHtmlString.Value)); + writer.WriteValue(value.Html()); + + writer.WritePropertyName(nameof(LocalizedHtmlString.IsResourceNotFound)); + writer.WriteValue(value.IsResourceNotFound); + + writer.WriteEndObject(); + } + + public override LocalizedHtmlString ReadJson( + JsonReader reader, + Type objectType, + LocalizedHtmlString existingValue, + bool hasExistingValue, + JsonSerializer serializer) + { + var token = JToken.Load(reader); + + if (token.Type == JTokenType.String) + { + var text = token.Value(); + return new LocalizedHtmlString(text, text); + } + + if (token is JObject jObject) + { + var name = jObject.GetMaybe(nameof(LocalizedHtmlString.Name))?.ToObject(); + var value = jObject.GetMaybe(nameof(LocalizedHtmlString.Value))?.ToObject() ?? name; + var isResourceNotFound = jObject.GetMaybe(nameof(LocalizedHtmlString.IsResourceNotFound))?.ToObject(); + + name ??= value; + if (string.IsNullOrEmpty(name)) throw new InvalidOperationException("Missing name."); + + return new LocalizedHtmlString(name, value, isResourceNotFound == true); + } + + throw new InvalidOperationException($"Can't parse token \"{token}\". It should be object or string"); + } +}