2020-04-19 22:26:20 +00:00
|
|
|
using System;
|
|
|
|
using System.Buffers;
|
|
|
|
using System.Buffers.Text;
|
|
|
|
using System.Globalization;
|
|
|
|
using System.Text.Json;
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
|
2020-05-22 16:48:01 +00:00
|
|
|
namespace MediaBrowser.Common.Json.Converters
|
2020-04-19 22:26:20 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// Long to String JSON converter.
|
|
|
|
/// Javascript does not support 64-bit integers.
|
|
|
|
/// </summary>
|
2020-05-22 16:48:01 +00:00
|
|
|
public class JsonInt64Converter : JsonConverter<long>
|
2020-04-19 22:26:20 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
2020-05-22 16:48:01 +00:00
|
|
|
/// Read JSON string as int64.
|
2020-04-19 22:26:20 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <param name="reader"><see cref="Utf8JsonReader"/>.</param>
|
|
|
|
/// <param name="type">Type.</param>
|
|
|
|
/// <param name="options">Options.</param>
|
|
|
|
/// <returns>Parsed value.</returns>
|
|
|
|
public override long Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
|
|
|
|
{
|
|
|
|
if (reader.TokenType == JsonTokenType.String)
|
|
|
|
{
|
|
|
|
// try to parse number directly from bytes
|
2020-05-22 16:48:01 +00:00
|
|
|
var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
|
|
|
|
if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed)
|
2020-04-19 22:26:20 +00:00
|
|
|
{
|
|
|
|
return number;
|
|
|
|
}
|
|
|
|
|
|
|
|
// try to parse from a string if the above failed, this covers cases with other escaped/UTF characters
|
|
|
|
if (long.TryParse(reader.GetString(), out number))
|
|
|
|
{
|
|
|
|
return number;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// fallback to default handling
|
|
|
|
return reader.GetInt64();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Write long to JSON string.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="writer"><see cref="Utf8JsonWriter"/>.</param>
|
|
|
|
/// <param name="value">Value to write.</param>
|
|
|
|
/// <param name="options">Options.</param>
|
|
|
|
public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
|
|
|
|
{
|
|
|
|
writer.WriteStringValue(value.ToString(NumberFormatInfo.InvariantInfo));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|