Skip to content
This repository was archived by the owner on Mar 26, 2025. It is now read-only.
Open
Show file tree
Hide file tree
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
21 changes: 21 additions & 0 deletions src/Dahomey.Json.Tests/DiscriminatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -262,5 +262,26 @@ public void ReadPolymorphicObjectWithDeferredTypeProperty()
Assert.Equal("foo", nameObject.Name);
Assert.Equal(1, nameObject.Id);
}

[Fact]
public void ReadPolymorphicObjectWithBaseRegister()
{
const string json = @"{""BaseObject"":{""$type"":12,""Name"":""foo"",""Id"":1}}";

JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();
DiscriminatorConventionRegistry registry = options.GetDiscriminatorConventionRegistry();
registry.ClearConventions();
registry.RegisterConvention(new DefaultDiscriminatorConvention<int>(options));
registry.RegisterType<BaseObject>();
registry.RegisterType<NameObject>();

BaseObjectHolder obj = JsonSerializer.Deserialize<BaseObjectHolder>(json, options);

Assert.NotNull(obj);
Assert.IsType<NameObject>(obj.BaseObject);
Assert.Equal("foo", ((NameObject)obj.BaseObject).Name);
Assert.Equal(1, obj.BaseObject.Id);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,17 @@ public void ClearConventions()

public IDiscriminatorConvention? GetConvention(Type type)
{
return _conventionsByType.GetOrAdd(type, t => InternalGetConvention(t));
if(_conventionsByType.TryGetValue(type, out IDiscriminatorConvention? convention))
{
return convention;
}

convention = InternalGetConvention(type);
if(convention != null)
{
_conventionsByType.TryAdd(type, convention);
}
return convention;
}

public void RegisterAssembly(Assembly assembly)
Expand Down