aboutsummaryrefslogtreecommitdiff
path: root/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
blob: 28437023fece1f79d527a5f08eb23b8db13a8a16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Jellyfin.Extensions.Json.Converters
{
    /// <summary>
    /// Converts a nullable struct or value to/from JSON.
    /// Required - some clients send an empty string.
    /// </summary>
    /// <typeparam name="TStruct">The struct type.</typeparam>
    public class JsonNullableStructConverter<TStruct> : JsonConverter<TStruct?>
        where TStruct : struct
    {
        /// <inheritdoc />
        public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            // Token is empty string.
            if (reader.TokenType == JsonTokenType.String
                && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty)
                    || (!reader.HasValueSequence && reader.ValueSpan.IsEmpty)))
            {
                return null;
            }

            return JsonSerializer.Deserialize<TStruct>(ref reader, options);
        }

        /// <inheritdoc />
        public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
            => JsonSerializer.Serialize(writer, value!.Value, options); // null got handled higher up the call stack
    }
}