diff options
| author | crobibero <cody@robibe.ro> | 2021-03-12 06:43:57 -0700 |
|---|---|---|
| committer | crobibero <cody@robibe.ro> | 2021-03-12 06:43:57 -0700 |
| commit | e814d8e2cfe41acb9269c048bbbd5f133dfcae7b (patch) | |
| tree | c46525396f225d51278793499ba66182379bdb4d /MediaBrowser.Common/Json/Converters/JsonStringConverter.cs | |
| parent | d7f0aaaec10aa642d1d73c87771c6089c19d0ab6 (diff) | |
Add JsonStringConverter
Diffstat (limited to 'MediaBrowser.Common/Json/Converters/JsonStringConverter.cs')
| -rw-r--r-- | MediaBrowser.Common/Json/Converters/JsonStringConverter.cs | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs new file mode 100644 index 000000000..585f52b8f --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs @@ -0,0 +1,38 @@ +using System; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Converter to allow the serializer to read strings. + /// </summary> + public class JsonStringConverter : JsonConverter<string> + { + /// <inheritdoc /> + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.TokenType switch + { + JsonTokenType.Null => null, + JsonTokenType.String => reader.GetString(), + _ => GetRawValue(reader) + }; + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + writer.WriteStringValue(value); + } + + private static string GetRawValue(Utf8JsonReader reader) + { + var utf8Bytes = reader.HasValueSequence + ? reader.ValueSequence.FirstSpan + : reader.ValueSpan; + return Encoding.UTF8.GetString(utf8Bytes); + } + } +}
\ No newline at end of file |
