序列化和反序列化代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了序列化和反序列化代码相关的知识,希望对你有一定的参考价值。

1.UserInfo对象类

[Serializable]
public class UserInfo
{
    public string Name { get; set; }
    public int Age { get; set; }
}

2.Xml方式序列化和反序列化

public class XmlSerialization
{
    public static void XmlSerialize(UserInfo user)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(UserInfo));
        StreamWriter sw = new StreamWriter("UserInfo.xml");
        serializer.Serialize(sw, user);
        sw.Close();
    }

    public static UserInfo XmlDeserialize()
    {
        XmlSerializer serializer = new XmlSerializer(typeof(UserInfo));
        FileStream fs = new FileStream("UserInfo.xml", FileMode.Open);
        UserInfo user = serializer.Deserialize(fs) as UserInfo;
        fs.Close();
        return user;
    }
}

3.Binary方式序列化和反序列化

public class RuntimeSerialization
{
    public static void BinarySerialize(UserInfo user)
    {
        FileStream fs = new FileStream(@"SerializeFile\UserInfo.bin", FileMode.Append);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(fs, user);
        fs.Close();
    }

    public static UserInfo BinaryDeserialize()
    {
        FileStream fs = new FileStream(@"SerializeFile\UserInfo.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
        BinaryFormatter formatter = new BinaryFormatter();
        UserInfo user = formatter.Deserialize(fs) as UserInfo;
        fs.Close();
        return user;
    }
}

 

以上是关于序列化和反序列化代码的主要内容,如果未能解决你的问题,请参考以下文章

序列化和反序列化的示例代码

csharp 此代码演示了json序列化和反序列化的4种方法

RestFramework

Django REST framework序列化

rest_framework

java反序列化引起的内存溢出怎么解决