Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
LonelyWindG opened this issue Aug 3, 2024 · 0 comments

Comments

@LonelyWindG
Copy link

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);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant