aaubry / YamlDotNet

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

Json Compatible Serialization does not produce JSON for nodes. #906

Open ShiJbey opened 4 months ago

ShiJbey commented 4 months ago

Describe the bug

I want to serialize a large tree of YamlNodes to a JSON string, but it seems that the Serializer either:

  1. Outputs YAML instead of JSON when attempting to serialize a YamlNode
  2. Outputs JSON with unexpected additional information ("RootNode" and "AllNodes") when attempting to serialize the same node wrapped in a YamlDocument

I want to manually create the node trees because of my game's structure. Creating serialized "proxy" objects feels like too much, but seems to be the only supported serialization route. I appreciate your help.

To Reproduce

The toy example below recreates both problems. For reference, I'm using version 15.1.1 binaries loaded into Unity. I first encountered the problem while using the Unity asset store package. I recently tried the binaries and still had the same problem.

YamlMappingNode node = new YamlMappingNode()
{
    {"ingredients", new YamlSequenceNode() { "sugar", "water", "purple" } }
};

YamlDocument doc = new YamlDocument(node);

var serializer = new SerializerBuilder()
    .JsonCompatible()
    .Build();

// Swap for Console.Write();

Debug.Log(serializer.Serialize(node));

Debug.Log(serializer.Serialize(doc));

The code above outputs the following to the console.

ingredients:
- sugar
- water
- purple
{"RootNode": {ingredients: [sugar, water, purple]}, "AllNodes": [{ingredients: [sugar, water, purple]}, ingredients, [sugar, water, purple], sugar, water, purple]}