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

How to fallback to another deserialization attempt in case of exceptions? #675

Closed
cdavernas opened this issue Feb 10, 2022 · 1 comment
Closed

Comments

@cdavernas
Copy link

cdavernas commented Feb 10, 2022

Hello everyone!

I was wondering: is something like the following doable in the current state of YamlDotNet? If yes, any idea how? If no, what do you think could be reasonable alternatives?
The idea is to try deserializing an object with a given type, and if it fails, fallback to another type.

The problem with the following code is that when the t1 deserialization attempt fails, the t2 attempt will use the reader that has already moved forward (with the t1 attempt), with no possibility (to my knowledge) to move back to previous position.

 public class OneOfDeserializer
        : INodeDeserializer
    {

        public OneOfDeserializer(INodeDeserializer inner)
        {
            this.Inner = inner;
        }

        protected INodeDeserializer Inner { get; }

        public virtual bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object> nestedObjectDeserializer, out object value)
        {
            value = null;
            var oneOfType = expectedType.GetGenericType(typeof(OneOf<,>));
            if(oneOfType == null)
                return this.Inner.Deserialize(reader, expectedType, nestedObjectDeserializer, out value);
            var t1 = oneOfType.GetGenericArguments()[0];
            var t2 = oneOfType.GetGenericArguments()[1];
            try
            {
                value = nestedObjectDeserializer(reader, t1);
            }
            catch
            {
                value = nestedObjectDeserializer(reader, t2);
            }
            value = Activator.CreateInstance(oneOfType, new object[] { value });
            return true;
        }

    }

Thanks in advance for the help!

@EdwardCooke
Copy link
Collaborator

No its not. All of YamlDotNet is forward only and it would be a large undertaking to undo that.

I'm going to close this for now, if you have additional comments, re-open it and we can discuss.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants