How to serialize a custom class with YamlDotNet

淺唱寂寞╮ 提交于 2019-11-30 09:43:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!