-
Notifications
You must be signed in to change notification settings - Fork 119
/
OptionalConverter.cs
49 lines (45 loc) · 1.76 KB
/
OptionalConverter.cs
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
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace DotNext.Text.Json;
/// <summary>
/// Represents JSON converter for <see cref="Optional{T}"/> data type.
/// </summary>
/// <typeparam name="T">The type of the value in <see cref="Optional{T}"/> container.</typeparam>
public sealed class OptionalConverter<T> : JsonConverter<Optional<T>>
{
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, Optional<T> value, JsonSerializerOptions options)
{
switch (value)
{
case { IsUndefined: true }:
throw new InvalidOperationException(ExceptionMessages.UndefinedValueDetected);
case { IsNull: true }:
writer.WriteNullValue();
break;
default:
var typeInfo = options.GetTypeInfo(typeof(T));
if (typeInfo is JsonTypeInfo<T?> typed)
{
JsonSerializer.Serialize(writer, value.ValueOrDefault, typed);
}
else
{
JsonSerializer.Serialize(writer, value.ValueOrDefault, typeInfo);
}
break;
}
}
/// <inheritdoc />
public override Optional<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
JsonTypeInfo typeInfo;
return new(
reader.TokenType is JsonTokenType.Null ?
default
: (typeInfo = options.GetTypeInfo(typeof(T))) is JsonTypeInfo<T?>
? JsonSerializer.Deserialize(ref reader, (JsonTypeInfo<T>)typeInfo)
: (T?)JsonSerializer.Deserialize(ref reader, typeInfo));
}
}