Only handle empty string or null case

pull/4033/head
crobibero 4 years ago
parent 9b2359a453
commit 1f2d73af8e

@ -1,6 +1,4 @@
using System; using System;
using System.Buffers;
using System.Buffers.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
@ -15,29 +13,15 @@ namespace MediaBrowser.Common.Json.Converters
/// <inheritdoc /> /// <inheritdoc />
public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{ {
if (reader.TokenType == JsonTokenType.String) switch (reader.TokenType)
{ {
ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; case JsonTokenType.String when (reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty:
if (Utf8Parser.TryParse(span, out int number, out int bytesConsumed) && span.Length == bytesConsumed) case JsonTokenType.Null:
{
return number;
}
var stringValue = reader.GetString().AsSpan();
// value is null or empty, just return null.
if (stringValue.IsEmpty)
{
return null; return null;
} default:
// fallback to default handling
if (int.TryParse(stringValue, out number)) return reader.GetInt32();
{
return number;
}
} }
return reader.GetInt32();
} }
/// <inheritdoc /> /// <inheritdoc />

@ -1,6 +1,4 @@
using System; using System;
using System.Buffers;
using System.Buffers.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
@ -22,32 +20,15 @@ namespace MediaBrowser.Common.Json.Converters
/// <returns>Parsed value.</returns> /// <returns>Parsed value.</returns>
public override long? Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) public override long? Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
{ {
if (reader.TokenType == JsonTokenType.String) switch (reader.TokenType)
{ {
// try to parse number directly from bytes case JsonTokenType.String when (reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty:
var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; case JsonTokenType.Null:
if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed)
{
return number;
}
var stringValue = reader.GetString().AsSpan();
// value is null or empty, just return null.
if (stringValue.IsEmpty)
{
return null; return null;
} default:
// fallback to default handling
// try to parse from a string if the above failed, this covers cases with other escaped/UTF characters return reader.GetInt64();
if (long.TryParse(stringValue, out number))
{
return number;
}
} }
// fallback to default handling
return reader.GetInt64();
} }
/// <summary> /// <summary>

Loading…
Cancel
Save