How to exclude single quotes around string with special characters when serializing using YamlDotNet

117 views Asked by At

I'm using YamlDotNet in C# to serialize to yaml. When I serialize string values like say "foo", it shows up as

dependsOn: foo

But when the value is "[]", it's always surrounded by single quotes

dependsOn: '[]'

this doesn't work for me in the context of Azure pipelines. It has to be without quotes.

dependsOn: []

How can I achieve this?

1

There are 1 answers

0
Kevin Lu-MSFT On

I can reproduce the similar situation when using the YAMLDotNet.

enter image description here

When the value contains the special characters, it will add single quotes to treat it as string.

It seems to be the default behavior of this .Net Library.

Other users also have reported the same issue in the Github feedback site: How to serialize the !include Directive in YamlDotNet. You can follow this ticket and wait for a reply from the developer

For a workaround, you can use the Replace method in C# to replace the '[]' to [].

For example:

public class Program
{
    public static void Main()
    {
        var serializer = new SerializerBuilder()
            .Build();

        var yaml = serializer.Serialize(new QuotedString { DependsOn = "[]" , teststring="test"});
        var newyaml = yaml.Replace("'[]'","[]");
        Console.WriteLine(newyaml);
    }
}

public class QuotedString
{
    [YamlMember(ScalarStyle = ScalarStyle.Plain)]
    public string DependsOn { get; set; }
    public string teststring { get; set; }
}

Result:

enter image description here