using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MediaBrowser.Common.Json.Converters
{
///
/// Parse JSON string as nullable long.
/// Javascript does not support 64-bit integers.
/// Required - some clients send an empty string.
///
public class JsonNullableInt64Converter : JsonConverter
{
///
/// Read JSON string as int64.
///
/// .
/// Type.
/// Options.
/// Parsed value.
public override long? Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.String when (reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty:
case JsonTokenType.Null:
return null;
default:
// fallback to default handling
return reader.GetInt64();
}
}
///
/// Write long to JSON long.
///
/// .
/// Value to write.
/// Options.
public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
{
if (value is null)
{
writer.WriteNullValue();
}
else
{
writer.WriteNumberValue(value.Value);
}
}
}
}