1

I'm trying to serialize a custom class with YamlDotNet library.
Here is my class:

public class Person
{
    string firstName;
    string lastName;

    public Person(string first, string last)
    {
        firstName = first;
        lastName = last;
    }
}

And here is how I tried to serialize it:

StreamWriter streamWriter = new StreamWriter("Test.txt");
Person person = new Person("toto", "titi");
Serializer serializer = new Serializer();
serializer.Serialize(streamWriter, person);

But in my output file, I only have this : { }

What did I forget to do to serialize my class?

Pang
  • 9,564
  • 146
  • 81
  • 122
YohDono
  • 25
  • 1
  • 7

1 Answers1

1

The default behavior of YamlDotNet is to serialize public properties and to ignore fields. The easiest fix is to replace the public fields with automatic properties:

public class Person
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }

    public Person(string first, string last)
    {
        FirstName = first;
        LastName = last;
    }
}

You could alter the behavior of YamlDotNet to serialize private fields relatively easily, but I do not recommend that.

Pang
  • 9,564
  • 146
  • 81
  • 122
Antoine Aubry
  • 12,203
  • 10
  • 45
  • 74
  • Thanks it's working now. But what if I don't want to serialize all my properties, there is a way to "hide" them from YamlDotNet ? – YohDono Feb 11 '15 at 14:57
  • 1
    Nevermind, I find the answer to my question. If someone else is looking for the answer, you have to add the attribute YamlIgnore to your properties. Thanks again for the help – YohDono Feb 11 '15 at 15:18
  • "Default behavior" implies that some type of non-default behavior is supported. In this case it's hard-coded, fixed behavior. It seems reasonable to support (at least optionally) serializing public fields. – Frank Smith Jan 14 '16 at 13:43
  • There is support for replacing this behavior, by providing a different implementation of the interface `ITypeInspector`. So yes, the default behavior is to consider only public properties, but you can implement any behavior you want. – Antoine Aubry Jan 15 '16 at 07:31