summaryrefslogtreecommitdiffstats
path: root/src/Cepis/LenientStringConverter.cs
blob: f76c917f6e8d6ddae1ef64d739c87c1e3178aebb (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
47
48
49
50
51
52
53
54
55
56
57
using System.Buffers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Cepis;

/// <summary>
/// Reads any scalar as a string, and a JSON <c>null</c> as the empty string.
/// </summary>
/// <remarks>
/// The API documents every text field as a string and an absent one as
/// <c>""</c>, never null. This converter makes a client that meets a
/// <c>null</c>, or a code sent as a number, degrade to the documented shape
/// instead of throwing: none of those is worth failing a whole lookup over.
/// </remarks>
internal sealed class LenientStringConverter : JsonConverter<string>
{
    public override bool HandleNull => true;

    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        switch (reader.TokenType)
        {
            case JsonTokenType.String:
                return reader.GetString() ?? "";
            case JsonTokenType.Null:
                return "";
            case JsonTokenType.True:
                return "true";
            case JsonTokenType.False:
                return "false";
            case JsonTokenType.Number:
                var raw = reader.HasValueSequence
                    ? reader.ValueSequence.ToArray()
                    : reader.ValueSpan.ToArray();
                return Encoding.UTF8.GetString(raw);
            default:
                throw new JsonException($"expected a string, got {reader.TokenType}");
        }
    }

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        ArgumentNullException.ThrowIfNull(writer);
        writer.WriteStringValue(value);
    }

    public override string ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
        reader.GetString() ?? "";

    public override void WriteAsPropertyName(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        ArgumentNullException.ThrowIfNull(writer);
        writer.WritePropertyName(value);
    }
}