Giter VIP home page Giter VIP logo

Comments (6)

olesmartyniuk avatar olesmartyniuk commented on May 18, 2024 2

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!

from yamldotnet.

aaubry avatar aaubry commented on May 18, 2024 1

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.

from yamldotnet.

aaubry avatar aaubry commented on May 18, 2024

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.

from yamldotnet.

vjelic avatar vjelic commented on May 18, 2024

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

from yamldotnet.

vjelic avatar vjelic commented on May 18, 2024

Hi Antoine,

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

Regards,
Vladimir

from yamldotnet.

vjelic avatar vjelic commented on May 18, 2024

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

from yamldotnet.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.