Adds support for nullable structs (#203)

This commit is contained in:
Kamron Batman 2020-08-29 18:47:00 -07:00 committed by GitHub
parent 259fdb5ae8
commit c4e7f47ada
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 0 deletions

View file

@ -0,0 +1,18 @@
namespace System.Text.Json.Serialization
{
public class NullableStructSerializer<TStruct> : JsonConverter<TStruct?> where TStruct : struct
{
public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType == JsonTokenType.Null
? default
: JsonSerializer.Deserialize<TStruct>(ref reader, options);
public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
{
if (value == null)
writer.WriteNullValue();
else
JsonSerializer.Serialize(writer, value.Value, options);
}
}
}