Reputation: 37
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?
Upvotes: 1
Views: 4807
Reputation: 12469
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.
Upvotes: 1