Skip to content

Detect all unregistered subtypes for a given json? #112

@norvegec

Description

@norvegec

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' },
  { }
]

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions