Waterboy4800
Waterboy4800

Reputation: 230

YamlDotNet SerializationOptions.EmitDefaults behaviour

I'm serializing an object with YamlDotNet with both reference and value types. What i'm looking to accomplish is that my integer values of zero remain in the outputted yaml, but null values would be discarded. EmitDefaults looks to discard '0' for numeric values. i understand null is the default value for reference types. Json.Net solved this with breaking it out into the following properties:

NullValueHandling = NullValueHandling.Ignore,

DefaultValueHandling = DefaultValueHandling.Ignore,

is there any way to accomplish the below?

class foo 
{
   int index {get;set;}
   string bar {get;set;}
}

new foo { index =0; bar = null } 
would yield the following yaml:
   index: 0

new foo { index =0; bar = "bar" } 
would yield the following yaml: 
   index: 0
   bar: bar

Thanks

Upvotes: 1

Views: 2282

Answers (2)

square_particle
square_particle

Reputation: 524

I know this was a long time ago, but for those that are wondering how to prevent null values from being serialized to text, you would want to use ConfigureDefaultValuesHandling when building the serializer. For instance:

    public string ToYaml(foo value)
    {
        var serializer = new SerializerBuilder()
            .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull)
            .Build();

        return serializer.Serialize(value);
    }

Upvotes: -1

Paul Chernoch
Paul Chernoch

Reputation: 5553

Not sure this is what you want, but this is how I force all default values to be serialized:

    public override string ToString()
    {
        var builder = new SerializerBuilder();
        builder.EmitDefaults(); // Force even default values to be written, like 0, false.
        var serializer = builder.Build();
        var strWriter = new StringWriter();
        serializer.Serialize(strWriter, this);
        return strWriter.ToString();
    }

Upvotes: 1

Related Questions