Merge pull request #4033 from crobibero/empty-string-nullable-number

Readd nullable number converters
This commit is contained in:
Bond-009 2020-09-01 21:41:46 +02:00 committed by GitHub
commit 506fc7cbae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 0 deletions

View File

@ -0,0 +1,44 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MediaBrowser.Common.Json.Converters
{
/// <summary>
/// Converts a nullable struct or value to/from JSON.
/// Required - some clients send an empty string.
/// </summary>
/// <typeparam name="T">The struct type.</typeparam>
public class JsonNullableStructConverter<T> : JsonConverter<T?>
where T : struct
{
private readonly JsonConverter<T?> _baseJsonConverter;
/// <summary>
/// Initializes a new instance of the <see cref="JsonNullableStructConverter{T}"/> class.
/// </summary>
/// <param name="baseJsonConverter">The base json converter.</param>
public JsonNullableStructConverter(JsonConverter<T?> baseJsonConverter)
{
_baseJsonConverter = baseJsonConverter;
}
/// <inheritdoc />
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Handle empty string.
if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
{
return null;
}
return _baseJsonConverter.Read(ref reader, typeToConvert, options);
}
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
{
_baseJsonConverter.Write(writer, value, options);
}
}
}

View File

@ -29,8 +29,14 @@ namespace MediaBrowser.Common.Json
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
// Get built-in converters for fallback converting.
var baseNullableInt32Converter = (JsonConverter<int?>)options.GetConverter(typeof(int?));
var baseNullableInt64Converter = (JsonConverter<long?>)options.GetConverter(typeof(long?));
options.Converters.Add(new JsonGuidConverter());
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new JsonNullableStructConverter<int>(baseNullableInt32Converter));
options.Converters.Add(new JsonNullableStructConverter<long>(baseNullableInt64Converter));
return options;
}