-
Notifications
You must be signed in to change notification settings - Fork 0
Yaml Deserialization
NebelFox edited this page Apr 5, 2022
·
3 revisions
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!
Make sure you have YamlDotNet
installed. Here is the Nuget Package
private static JsonElement YamlToJson(string filepath)
{
var yamlObject = new DeserializerBuilder().Build().Deserialize(new StreamReader(filepath));
return JsonSerializer.Deserialize<JsonElement>(new SerializerBuilder().JsonCompatible().Build().Serialize());
}
private static JsonElement YamlToJson(string filepath)
{
return JsonSerializer.Deserialize<JsonElement>(new SerializerBuilder().JsonCompatible().Build().Serialize(new DeserializerBuilder().Build().Deserialize(new StreamReader(filepath))));
}
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;
// 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);
}
- General:
- File Specification:
- Templates:
- Tips