YamlDotNet icon indicating copy to clipboard operation
YamlDotNet copied to clipboard

Parsing an int or bool from a YAML file

Open pvandervelde opened this issue 11 years ago • 2 comments

Based on the comment here: https://github.com/aaubry/YamlDotNet/issues/101#issuecomment-50288845

I created a type resolver like this (i.e. almost a copy of what was in the comment)

internal sealed class ScalarYamlNodeTypeResolver : INodeTypeResolver
{
    bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
    {
        if (currentType == typeof(string))
        {
            var scalar = nodeEvent as Scalar;
            if ((scalar != null) && (scalar.Style == ScalarStyle.Plain))
            {
                // 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(double);
                    return true;
                }

                // Add more cases here if needed
            }
        }

        return false;
    }
}

And using it like:

using (var input = new StreamReader(filePath))
{
    var deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());
    deserializer.TypeResolvers.Add(new ScalarYamlNodeTypeResolver());
    var definition = deserializer.Deserialize<RuleDefinition>(input);

    return definition;
}

The goal is to parse a section of YAML looking like:


---
    name: "Name"
    description: "Description"
    enabled: true

    signal:
        id: "Signal"
        parameters:
            bar: "stuff"

    condition:
        - name: "bar"
          type: "greaterthan"
          pattern : 10

    action:
        id: "Action"
        parameters:
            foo: "bar"

Where the class used to store the condition list elements is defined as:

/// <summary>
/// Stores information about a condition under which a given signal applies to a rule.
/// </summary>
public class ConditionRuleDefinition
{
    /// <summary>
    /// Gets or sets the name of the trigger parameter.
    /// </summary>
    public string Name
    {
        get;
        set;
    }

    /// <summary>
    /// Gets or sets the pattern to compare with.
    /// </summary>
    public object Pattern
    {
        get;
        set;
    }

    /// <summary>
    /// Gets or sets the comparison method.
    /// </summary>
    public string Type
    {
        get;
        set;
    }
}

Unfortunately I'm always getting a string object being put in the Pattern property and not an integer as I expected. Is there anything else I need to do in order to parse the Pattern as an integer when the value is not quoted but a string if it is?

pvandervelde avatar Jul 03 '15 04:07 pvandervelde

I ran your code through a debugger and found that at this point in your code if (currentType == typeof(string)) currentType is always of type System.Object. I haven't used this library for more than 15 minutes, but by changing your code to this

internal sealed class ScalarYamlNodeTypeResolver : INodeTypeResolver
{
    // Expressions taken from https://github.com/aaubry/YamlDotNet/blob/feat-schemas/YamlDotNet/Core/Schemas/JsonSchema.cs
    private Regex isIntRegex = new Regex(@"^-?(0|[1-9][0-9]*)$", RegexOptions.IgnorePatternWhitespace);
    private Regex isDoubleRegex = new Regex(@"^-?(0|[1-9][0-9]*)(\.[0-9]*)?([eE][-+]?[0-9]+)?$", RegexOptions.IgnorePatternWhitespace);

    bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref System.Type currentType)
    {
        var scalar = nodeEvent as Scalar;
        if ((scalar != null) && (scalar.Style == ScalarStyle.Plain))
        {
            if (isIntRegex.IsMatch(scalar.Value))
            {
                currentType = typeof(int);
                return true;
            }

            if (isDoubleRegex.IsMatch(scalar.Value))
            {
                currentType = typeof(double);
                return true;
            }
        }

        return false;
    }
}

Saving the Regex checks as objects should alleviate some of the penalty you get from always checking for matches...

mswf avatar Jun 07 '16 13:06 mswf

Closing this because the issue probably no longer exists. Please open a new issue if you still encounter this bug.

aaubry avatar Aug 30 '16 22:08 aaubry