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

Detect all unregistered subtypes for a given json? #112

Open
norvegec opened this issue Jul 25, 2020 · 0 comments
Open

Detect all unregistered subtypes for a given json? #112

norvegec opened this issue Jul 25, 2020 · 0 comments

Comments

@norvegec
Copy link

norvegec commented Jul 25, 2020

This nice library helps me to register a polymorphic tree of (with string discriminator property Type and "unlimited" nested steps that implements the same IStep interface).
During deserialization of such tree, I'd like to "detect" all objects that don't have (supported) Type. And it should not throw on a first (mis-)match.
As of today, I did not find any better than either traverse a tree again or use a "trap" fallback type (In constructor it adds each "unknown" Type to a static list. (non-multithreading solution that requires a cleanup after deserialization).

What do you think could be a better solution to this?

I'm thinking about adding a support for invoking a (registered) delegate or raising (weak) event or notifying an observable.
It could be done in addition to JsonSubtypesConverterBuilder.SetFallbackSubtype(Type) and JsonSubtype.ResolveType() looks like a perfect extension point.

*** Source/destination types

public interface IStep
{
    string Type { get; set; }
    IList<IStep> Steps { get; set; }
}

private static JsonConverter CreateStepsJsonConverter(Assembly assemblyToScan)
{
    var stepTypes = GetImplementorsOf<IStep>(assemblyToScan);

    var builder = JsonSubtypesConverterBuilder.Of(
        baseType: typeof(IStep),
        discriminatorProperty: nameof(IStep.Type));

    builder.SetFallbackSubtype(typeof(UnknownStepsTrap));

    foreach (Type subType in stepTypes)
    {
         string discriminatorPropertyValue = subType.Name;
         builder.RegisterSubtype(subType, discriminatorPropertyValue);
    }
    return builder.Build();
}

*** Source/destination JSON

[ 
  { 'Type': 'NonExistentType42' },
  { 'Type': 'RegisteredType' },
  { }
]
@manuc66 manuc66 added this to the 1.9.0 milestone Feb 26, 2021
@manuc66 manuc66 removed this from the 1.9.0 milestone Oct 22, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants