Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trivial deserialization failing with YamlDotNet

Tags:

yamldotnet

What can possible go wrong with this:

    public void Main()
    {
        var input = new StringReader(Document);

        var deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());
        var p = deserializer.Deserialize<Person>(input);

        Console.WriteLine(p.Name);
    }

    public class Person
    {
        public string Name {get;set;}
    }

    private const string Document = @"Name: Peter";

A serialization exception is thrown:

Property 'Name' not found on type 'YamlDotNet.Samples.DeserializeObjectGraph+Person'

The same happens if I first serialize a Person object using the Serializer.

While the online sample for deserialization works just fine - this trivial code does not. What am I missing? It must be a stupid little detail. (But it happened before with other data structures I tried.)

like image 325
RalfW Avatar asked Feb 10 '23 22:02

RalfW


2 Answers

As it seems, the problem is with the namingConvention parameter. If I don't set it to an instance of CamelCaseNamingConvention all is fine.

Unfortunately the "canonical" example (https://dotnetfiddle.net/HD2JXM) uses it and thus suggests it is important.

like image 62
RalfW Avatar answered Mar 19 '23 21:03

RalfW


For any reason the CamelCaseNamingConvention converts the fields to lowercase in the class (ie. 'Name' to 'name'). As the string is 'Name' and not 'name' the deserialization fails. The example uses lower-case therefore it works.... I had the same problem....

like image 21
Mungo64 Avatar answered Mar 19 '23 22:03

Mungo64