问题
I'm trying to serialize a custom class with YamlDotNet library.
There is my class :
public class Person
{
string firstName;
string lastName;
public Person(string first, string last)
{
firstName = first;
lastName = last;
}
}
And there 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 I forgot to do to serialize my class ?
Thanks in advance
回答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.
来源:https://stackoverflow.com/questions/28453700/how-to-serialize-a-custom-class-with-yamldotnet