Skip to content

Commit

Permalink
Update PolymorphicConverter.cs
Browse files Browse the repository at this point in the history
  • Loading branch information
dferretti authored Dec 19, 2020
1 parent 77fbb00 commit 297c950
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions PolymorphicConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ namespace SystemTextJsonPolymorphicDeserialization
{
public class PolymorphicConverter : JsonConverter<BaseModel>
{
private readonly string _discriminator;
private readonly byte[] _discriminatorUtf8;

public PolymorphicConverter(string discriminator)
{
this._discriminator = discriminator;
this._discriminatorUtf8 = System.Text.Encoding.UTF8.GetBytes(discriminator);
}

public readonly Dictionary<string, Type> TypeMapping = new Dictionary<string, Type> {
{ "Bar", typeof(BarModel) },
{ "Foo", typeof(FooModel) }
Expand All @@ -22,7 +31,7 @@ public class PolymorphicConverter : JsonConverter<BaseModel>
Type? deserializedType = null;
while(typeReader.Read())
{
if(typeReader.TokenType == JsonTokenType.PropertyName && typeReader.GetString() == "Type")
if(typeReader.TokenType == JsonTokenType.PropertyName && typeReader.ValueTextEquals(this._discriminatorUtf8))
{
if(!typeReader.Read())
{
Expand All @@ -47,7 +56,7 @@ public class PolymorphicConverter : JsonConverter<BaseModel>

if(deserializedType == null)
{
throw new JsonException($"Key 'Type' not found.");
throw new JsonException($"Key '{this._discriminator}' not found.");
}

return (BaseModel?)JsonSerializer.Deserialize(ref reader, deserializedType, options);
Expand All @@ -58,4 +67,4 @@ public override void Write(Utf8JsonWriter writer, BaseModel value, JsonSerialize
throw new NotImplementedException();
}
}
}
}

0 comments on commit 297c950

Please sign in to comment.