-
-
Notifications
You must be signed in to change notification settings - Fork 461
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 do I parse only part of YAML into an object? #599
Comments
This code should help you. The trick is to use the parser to scan to the point where you would like to deserialize. https://dotnetfiddle.net/EitE4O using System;
using System.IO;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
var yaml = @"
config_one:
name: foo
stuff: value
config_two:
name: bar
random: value";
var parser = new Parser(new StringReader(yaml));
var deserializer = new DeserializerBuilder()
.WithNamingConvention(new CamelCaseNamingConvention())
.Build();
parser.Consume<StreamStart>();
parser.Consume<DocumentStart>();
parser.Consume<MappingStart>();
while (parser.TryConsume<Scalar>(out var key))
{
if (key.Value == "config_two")
{
var config = deserializer.Deserialize<ConfigTwo>(parser);
Console.WriteLine(config.Random);
}
else
{
parser.SkipThisAndNestedEvents();
Console.WriteLine($"Skipped {key.Value}");
}
}
class ConfigTwo
{
public string Name { get; set; }
public string Random { get; set ;}
} |
Minor detail, but I found that because I'm deserializing, I have to use |
Thanks again for the solution. I changed my YAML slightly, but I still need to accomplish the same task (only parse config_one:
name: foo
stuff: value
config_two:
- name: bar1
random: value1
- name: bar2
random: value2 Doing this does not work: var config = deserializer.Deserialize<List<ConfigTwo>>(parser); |
Sorry for the false positive. This actually does work, but it breaks when enum PossibleNames { Bar1, Bar2 }
class ConfigTwo
{
public PossibleNames? Name { get; set; }
}; I made it nullable to express that this property in YAML is optional. You don't have to provide |
Found the solution in #544. Hopefully that gets proper support by the library in the future. I'm closing now since my question is answered. Thanks again! |
The problem with nullable enums should be fixed once #600 is merged :) |
Suppose I have the following YAML:
I want to selectively parse
config_one
into an object and I wantconfig_two
to be ignored:How can I do this? The documentation is pretty lacking, or at least, it uses a lot of terminology that doesn't make much sense to me, and thus I was not able to search for this functionality.
The text was updated successfully, but these errors were encountered: