0

YamlDotNet can deserialize a yaml document which contain json.

Suppose there is a yaml document as input like below.

fieldA: a
fieldB:
  - { "subFieldA": "a1","subFieldB": "b1" }
  - { "subFieldA": "a2","subFieldB": "b2" }

Then, I deserialize it and re-serialize.

class Program
{
    static void Main(string[] args)
    {
        using var sr = new StreamReader("test.yaml");
        var deserializer = new DeserializerBuilder()
            .WithNamingConvention(CamelCaseNamingConvention.Instance)
            .Build();
        var output = deserializer.Deserialize<Temp>(sr);
        var serializer = new SerializerBuilder()
            .Build();
        Console.WriteLine(serializer.Serialize(output));
    }
}

public class Temp
{
    public string FieldA { get; set; }
    public List<Dictionary<string, string>> FieldB { get; set; }
}

I would get output like below.

FieldA: a
FieldB:
  - subFieldA: a1
    subFieldB: b1
  - subFieldA: a2
    subFieldB: b2

But I want the property FieldB still be serialized to json. In other words, I want to get a output same as input.

Is there a way to use YamlDotNet to achieve this effect, please?

Zalasento
  • 1
  • 2

1 Answers1

1

YamlDotNet is only used for serializing and deserializing YAML. Use the .NET serialization library if all you want to do is actually serialize that dictionary. Obviously the string property cannot do anything with unless it's part of the dictionary.

using System.Text.Json;

var temp = new Temp();
temp.Dict = new Dictionary<string, string>();
temp.Dict.Add("hello", "world");

string json = JsonSerializer.Serialize(temp.Dict);

If you're asking if you can put JSON into YAML, sure, just turn it into a json string first, and add that string as a property of a separate class to serialize into YAML. I don't believe there's a way to automatically get a YAML library to be serializing portions of its stuff into JSON. You can't mix and match.

Brian Reading
  • 449
  • 5
  • 16