Skip to content
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

#112 - Inheritance with RegisterAssembly depends on class order #115

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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