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

TypeResolvers #101

Closed
vjelic opened this issue Jul 18, 2014 · 6 comments
Closed

TypeResolvers #101

vjelic opened this issue Jul 18, 2014 · 6 comments

Comments

@vjelic
Copy link

vjelic commented Jul 18, 2014

Hi,

I am using YamlDotNet to read my yaml files and it works excellent,
but it would be great if I could convert YamlNodes into .Net types such as int, float, string , List or Dictionary.

I can see that you have implemented TypeResolvers wich have method Resolve.
Do you have plans to continue with work on this method so that it could return .Net types?
Have you any suggestions that could help me?

Best regards,
Vladimir

@aaubry
Copy link
Owner

aaubry commented Jul 18, 2014

Hello,

There is support to deserialize YAML documents into objects, as well as serializing them back to YAML. You need to use the Deserializer class.

The YamlNode et al present an object model that maps to the document structure, similar to XmlNode. That's why serialization / deserialization is independent of these.

Unfortunately, the examples are lacking, but take a look at the unit tests in https://github.com/aaubry/YamlDotNet/blob/master/YamlDotNet.Test/Serialization/SerializationTests.cs.

Please reopen the issue if you have further questions. Thanks.

@aaubry aaubry closed this as completed Jul 18, 2014
@vjelic
Copy link
Author

vjelic commented Jul 25, 2014

Hi Antoine,

Thank you very much for your help.
I have one more question.
Part of my yaml file content looks like this:
"- - 1
- 233
- 1.0.0.5"

I am deserializing it using this command:
var stream = Yaml.StreamFrom("my_file.yaml");
var result = Deserializer.Deserialize(stream);

And I get this result:
['1', '233', '1.0.0.5']

As you can see all three objects in list are of type string.
Is there a way to implicitly convert first two objects into integer (int) type without explicitly specifying their types or without using tags in my yaml file.
If there is no way to do this do you have in plan to implement that kind of deserialization.
This is important to me because I have to read files which structure I don't know in advance so I can't explicitly provide types in source code when deserializing scalar nodes.

Best regards,
Vladimir

@aaubry
Copy link
Owner

aaubry commented Jul 27, 2014

Hi,

The behavior that you describe is what the YAML specification 1.2 mandates. Using the JSON schema or the Core schema you would get the desired behavior. However, that support is still work in progress. For now, you can still achieve what you want by creating a new type resolver:

public class ScalarNodeTypeResolver : INodeTypeResolver
{
    bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
    {
        if (currentType == typeof(object))
        {
            var scalar = nodeEvent as Scalar;
            if(scalar != null)
            {
                // Expressions taken from https://github.com/aaubry/YamlDotNet/blob/feat-schemas/YamlDotNet/Core/Schemas/JsonSchema.cs

                if(Regex.IsMatch(scalar.Value, @"^(true|false)$", RegexOptions.IgnorePatternWhitespace)
                {
                    currentType = typeof(bool);
                    return true;
                }

                if(Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* )$", RegexOptions.IgnorePatternWhitespace)
                {
                    currentType = typeof(int);
                    return true;
                }

                if(Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* ) ( \. [0-9]* )? ( [eE] [-+]? [0-9]+ )?$", RegexOptions.IgnorePatternWhitespace)
                {
                    currentType = typeof(float);
                    return true;
                }

                // Add more cases here if needed
            }
        }
        return false;
    }
}

Next, you just need to register it on the deserializer:

var deserializer = new Deserializer();
deserializer.TypeResolvers.Add(new ScalarNodeTypeResolver());
var result = deserializer.Deserialize(stream);

You should get the result that you expected: [ 1, 233, "1.0.0.5" ]
I hope this helps you.

@vjelic
Copy link
Author

vjelic commented Jul 31, 2014

Hi Antoine,

This is just what I needed.
Thank you very much for your help.

Regards,
Vladimir

@vjelic
Copy link
Author

vjelic commented Aug 12, 2014

Hi Antoine,

There is another problem, so I need your help again.

I have input yaml file that looks like this:

  • - 2
    • '6.0'
    • false
  • - 3
    • '6.1'
    • false

I use YamlDotNet to read this input file and immediately writes it to another file without changing the content.
Content of the output file looks like this:

  • - 2
    • 6.0
    • false
  • - 3
    • 6.1
    • false

As you can see there is difference between input and output file, i.e., in output file are missing single quotes around 6.0 and 6.1 strings.

Code that I am using for reading and writing to file is this:

// Reading form input file
string path = @"C:\input.yaml";
var fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
var stream = new System.IO.StreamReader(fs);
var deserializer = new Deserializer();
var result = deserializer.Deserialize(stream);

// Writing to output file
var serializer = new Serializer();
System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\output.yaml");
serializer.Serialize(file, result);
file.Close();

I tried to use all options from enum SerializationOptions, but did not achieve the desired goal (I wanted to completely keep unchanged the content of the input file).
Am I doing something wrong or am I missing some options when serializing and writing to output file?

Regards,
Vladimir

P.S. I have attached screenshot of the input and output files because there are bullets appearing in examples that I pasted in this comment.

input and output yaml files

@olesmartyniuk
Copy link

olesmartyniuk commented Dec 12, 2018

I also had the same issue and I found a solution that suitable for me. If little bit correct the condition in the code sample provided by Antoine we can ignore values in YAML document that are quoted and should not be converted to simple types such as bool or int.
So, if (scalar != null) we should replace on if (scalar != null && !scalar.IsQuotedImplicit) and all works fine!

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

3 participants