Skip to content

Fix nullable struct enum deserialization #563

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions src/JsonRpc/Serialization/Converters/EnumLikeStringConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,34 @@ internal class EnumLikeStringConverter : JsonConverter<IEnumLikeString>
{
public override void WriteJson(JsonWriter writer, IEnumLikeString value, JsonSerializer serializer) => new JValue(value.ToString()).WriteTo(writer);

public override IEnumLikeString ReadJson(
public override IEnumLikeString? ReadJson(
JsonReader reader, Type objectType, IEnumLikeString existingValue,
bool hasExistingValue,
JsonSerializer serializer
) =>
reader.TokenType switch {
JsonToken.String => (IEnumLikeString) Activator.CreateInstance(objectType, (string) reader.Value),
JsonToken.String => (IEnumLikeString?) CreateEnumLikeString(objectType, (string?) reader.Value),
_ => (IEnumLikeString) Activator.CreateInstance(objectType, null)
};

public override bool CanRead => true;

private static object? CreateEnumLikeString(Type objectType, string? value)
{
if (objectType.IsGenericType
&& objectType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// TODO: If the value is null, should we return null? ReadJson()'s return type isn't nullable...
if (value is null)
{
return null;
}

// We could also create a Nullable<T>, but then will that be an IEnumLikeString?
return Activator.CreateInstance(objectType.GetGenericArguments()[0], value);
}

return Activator.CreateInstance(objectType, value);
}
}
}