aaubry / YamlDotNet

YamlDotNet is a .NET library for YAML
MIT License
2.48k stars 466 forks source link

Add quotes for strings on model serialization #869

Closed sunnamed434 closed 7 months ago

sunnamed434 commented 7 months ago

I want to add quotes for strings when serializing a model (class), but adding attributes on properties is not my case - because I want it automated.

I checked issues on this GitHub repo and stackoverflow to find answers to my question, but without success, I saw solutions but they either did not work or just added the quotes for everything.

I think about smth like this, I guess there should be a way to do that via event emitter or in another way.

var yamlSerializer = new SerializerBuilder()
                        .WithQuotesForStrings()
                        .Build();
Before:

- Id: Item1
  Value: Hello world 1!
- Id: Item2
  Value: Hello world 2!
- Id: Item3
  Value: 10
- Id: Item4
  Value: true

After:

- Id: "Item1"
  Value: "Hello world 1!"
- Id: "Item2"
  Value: "Hello world 2!"
- Id: "Item3"
  Value: 10
- Id: "Item4"
  Value: true
EdwardCooke commented 7 months ago

I’m pretty sure there’s a withdefaultquountingstyle method on the serializerbuilder that was added recently.

EdwardCooke commented 7 months ago

It’s DefaultScalarStyle

https://github.com/aaubry/YamlDotNet/blob/847230593e95750d4294ca72c98a4bd46bdcf265/YamlDotNet/Serialization/SerializerBuilder.cs#L126C16-L126C16

sunnamed434 commented 7 months ago

Thanks, solved!

var yamlSerializer = new SerializerBuilder()
                        .WithNamingConvention(CamelCaseNamingConvention.Instance)
                        .WithDefaultScalarStyle(ScalarStyle.DoubleQuoted) // add this line
                        .Build();