aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableInt32Converter.cs
blob: 19d90b9a1b222f15fa858444c70329d13a7046e7 (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
34
35
36
37
38
39
40
41
42
43
44
45
46
#nullable enable

using System;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace MediaBrowser.Providers.Plugins.Omdb
{
    /// <summary>
    /// Converts a string <c>N/A</c> to <c>string.Empty</c>.
    /// </summary>
    public class JsonOmdbNotAvailableInt32Converter : JsonConverter<int?>
    {
        /// <inheritdoc />
        public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                var str = reader.GetString();
                if (str == null || str.Equals("N/A", StringComparison.OrdinalIgnoreCase))
                {
                    return null;
                }

                var converter = TypeDescriptor.GetConverter(typeToConvert);
                return (int?)converter.ConvertFromString(str);
            }

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

        /// <inheritdoc />
        public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
        {
            if (value.HasValue)
            {
                writer.WriteNumberValue(value.Value);
            }
            else
            {
                writer.WriteNullValue();
            }
        }
    }
}