aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs
diff options
context:
space:
mode:
authorBond-009 <bond.009@outlook.com>2021-03-20 00:48:41 +0100
committerJoshua M. Boniface <joshua@boniface.me>2021-03-21 19:10:13 -0400
commit679d3f58731c866b9be555db82e4c5410ca0850a (patch)
treeb21d4389b6d56b49ce7c1b2e4f831d4750a9bea7 /MediaBrowser.Common/Json/Converters/JsonStringConverter.cs
parent787ad44323c211d90499c2f40ae3434540cba321 (diff)
Merge pull request #5504 from crobibero/json-string-converter
(cherry picked from commit 1a0ce16f4d18b9a7850b52b299b4e6da15d40c53) Signed-off-by: Joshua M. Boniface <joshua@boniface.me>
Diffstat (limited to 'MediaBrowser.Common/Json/Converters/JsonStringConverter.cs')
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonStringConverter.cs39
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