diff options
| author | Bond-009 <bond.009@outlook.com> | 2021-03-20 00:48:41 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-03-20 00:48:41 +0100 |
| commit | 1a0ce16f4d18b9a7850b52b299b4e6da15d40c53 (patch) | |
| tree | e1ffeef3bd01f07e2b70e6e6b30f6e10175c243d /MediaBrowser.Common/Json/Converters/JsonStringConverter.cs | |
| parent | 9360fecb316973181a120027f70b311b219740cd (diff) | |
| parent | 37b1b31a46e818cb5d229ebf11d7db7895c3b964 (diff) | |
Merge pull request #5504 from crobibero/json-string-converter
Diffstat (limited to 'MediaBrowser.Common/Json/Converters/JsonStringConverter.cs')
| -rw-r--r-- | MediaBrowser.Common/Json/Converters/JsonStringConverter.cs | 39 |
1 files changed, 39 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..669b3cd07 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs @@ -0,0 +1,39 @@ +using System; +using System.Buffers; +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.ToArray() + : reader.ValueSpan; + return Encoding.UTF8.GetString(utf8Bytes); + } + } +}
\ No newline at end of file |
