YamlDotNet icon indicating copy to clipboard operation
YamlDotNet copied to clipboard

How can I serialize to get a pretty json or flow yaml format string with newlines?

Open LonelyWindG opened this issue 6 months ago • 0 comments

I wasn't able to find a similar question that would help me out, so what do I do please?

First, here's what I'd like to see happen:

  • json
{
    "key1": "value1",
    "key2": "value2"
}
  • flow yaml
{
    key1: value1,
    key2: value2
}

However, the result is always a line of json or flow yaml without line breaks and indentation:

json

{"key1": "value1", "key2": "value2"}

flow yaml

{key1: value1, key2: value2}

Here are some of my attempts:

static void Main()
{
    Serialize(true);
    Serialize(false);
}

static void Serialize(bool json)
{
    var mapping = new Dictionary<string, string>()
    {
        { "key1", "value1" },
        { "key2", "value2" }
    };

    var emitterSetting = EmitterSettings.Default
        .WithoutAnchorName()
        .WithIndentedSequences()
        .WithBestIndent(4)
        .WithNewLine("\n");

    var builder = new SerializerBuilder();
    if (json)
    {
        builder.JsonCompatible();
    }
    else
    {
        builder.WithEventEmitter(v => new FlowStyleEmitter(v));
    }

    var serializer = Serializer.FromValueSerializer(builder.BuildValueSerializer(), emitterSetting);
    var yaml = serializer.Serialize(mapping);
    Console.WriteLine(yaml);
}

public class FlowStyleEmitter(IEventEmitter nextEmitter) : ChainedEventEmitter(nextEmitter)
{
    public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter)
    {
        eventInfo.Style = YamlDotNet.Core.Events.MappingStyle.Flow;
        base.Emit(eventInfo, emitter);
    }
}

LonelyWindG avatar Aug 03 '24 06:08 LonelyWindG