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

Support read-only collection interfaces #236

Open
ejball opened this issue Jan 23, 2017 · 2 comments
Open

Support read-only collection interfaces #236

ejball opened this issue Jan 23, 2017 · 2 comments

Comments

@ejball
Copy link

ejball commented Jan 23, 2017

It would be great if the library could deserialize into properties of the following interfaces:

@mparry
Copy link

mparry commented May 21, 2020

@aaubry - I was interested in this feature and was thinking about coming up with a PR. Would you be able to offer any hints as to what changes might be required? I thought it might just be a case of adding these extra interfaces to DefaultObjectFactory but, after playing around with a customised version via WithObjectFactory(), I don't know if it's that simple.

Edit: ah, it seems like WithNodeTypeResolver() is actually the way forward.

@mparry
Copy link

mparry commented May 21, 2020

In the meantime, hooking the below in via WithNodeTypeResolver() seems to work well.

public sealed class ReadOnlyCollectionNodeTypeResolver : INodeTypeResolver
{
    public bool Resolve(NodeEvent nodeEvent, ref Type type)
    {
        if (type.IsInterface && type.IsGenericType && CustomGenericInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out var concreteType))
        {
            type = concreteType.MakeGenericType(type.GetGenericArguments());
            return true;
        }
        return false;
    }
    private static readonly IReadOnlyDictionary<Type, Type> CustomGenericInterfaceImplementations = new Dictionary<Type, Type>
    {
        {typeof(IReadOnlyCollection<>), typeof(List<>)},
        {typeof(IReadOnlyList<>), typeof(List<>)},
        {typeof(IReadOnlyDictionary<,>), typeof(Dictionary<,>)}
    };
}

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

3 participants