Merge pull request #5504 from crobibero/json-string-converter

(cherry picked from commit 1a0ce16f4d)
Signed-off-by: Joshua M. Boniface <joshua@boniface.me>
This commit is contained in:
Bond-009
2021-03-20 00:48:41 +01:00
committed by Joshua M. Boniface
parent 787ad44323
commit 679d3f5873
3 changed files with 80 additions and 1 deletions

View File

@@ -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);
}
}
}

View File

@@ -40,7 +40,8 @@ namespace MediaBrowser.Common.Json
new JsonStringEnumConverter(),
new JsonNullableStructConverterFactory(),
new JsonBoolNumberConverter(),
new JsonDateTimeConverter()
new JsonDateTimeConverter(),
new JsonStringConverter()
}
};