Skip to content

Yaml Deserialization

NebelFox edited this page Apr 5, 2022 · 3 revisions

Overview

Yaml deserialization is not built-in. However, you can easily implement it! All you need is to convert a yaml to json. Here is a method for this!

Requirements

Make sure you have YamlDotNet installed. Here is the Nuget Package

Short Form

private static JsonElement YamlToJson(string filepath)
{
    var yamlObject = new DeserializerBuilder().Build().Deserialize(new StreamReader(filepath));
    return JsonSerializer.Deserialize<JsonElement>(new SerializerBuilder().JsonCompatible().Build().Serialize());
}

One-Liner

private static JsonElement YamlToJson(string filepath)
{
    return JsonSerializer.Deserialize<JsonElement>(new SerializerBuilder().JsonCompatible().Build().Serialize(new DeserializerBuilder().Build().Deserialize(new StreamReader(filepath))));
}

Usage

var deserializer = new Deserializer();
// use converted yaml
deserializer.Deserialize(YamlToJson("verbox.yaml"));
BoxBuilder builder = deserializer.Boxes["box-name"];
/* ... */

Note. You may encounter name conflict with yaml deserializer and verbox deserializer, as they both name the same. Use alias to resolve it, e.g.

using YamlDeserializer = YamlDotNet.Serialization.Deserializer;
using Deserializer = Verbox.Deserialization.Deserializer;

Explained Form

// deserializes yaml file to JsonElement
private static JsonElement YamlToJson(string filepath)
{
    // JsonElement is accepted by Verbox.Deserialization.Deserializer
    // create a yaml deserializer
    var yamlDeserializer = new DeserializerBuilder().Build();
    // use it do read your yaml file into object
    object yamlObject = yamlDeserializer.Deserialize(new StreamReader(filepath));
    // create a yaml serializer
    Serializer yamlSerializer = new SerializerBuilder().JsonCompatible().Build();
    // serialize obtained object to json string
    string json = yamlSerializer.Serialize(yamlObject);
    // deserialize the json string to JsonElement
    return JsonSerializer.Deserialize<JsonElement>(json);
}
Clone this wiki locally