-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5d779c6
commit ab19b4a
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
56 changes: 56 additions & 0 deletions
56
Lombiq.HelpfulLibraries.AspNetCore/Localization/LocalizedHtmlStringConverter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<LocalizedHtmlString> | ||
{ | ||
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<string>(); | ||
return new LocalizedHtmlString(text, text); | ||
} | ||
|
||
if (token is JObject jObject) | ||
{ | ||
var name = jObject.GetMaybe(nameof(LocalizedHtmlString.Name))?.ToObject<string>(); | ||
var value = jObject.GetMaybe(nameof(LocalizedHtmlString.Value))?.ToObject<string>() ?? name; | ||
var isResourceNotFound = jObject.GetMaybe(nameof(LocalizedHtmlString.IsResourceNotFound))?.ToObject<bool>(); | ||
|
||
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"); | ||
} | ||
} |