保存数据契约序列化对象作为字符串保存在sql数据库中
本文关键字:保存 存在 sql 数据库 字符串 数据 契约 序列化 对象 | 更新日期: 2023-09-27 18:16:20
我有一个自定义类型UserSettingConfig,我想保存在我的数据库中,我想把它保存为纯XML,因为类型以后可能会改变,迁移纯XML比二进制对象更容易。
public class Serialize
{
private readonly DataContractSerializer _serializer;
public Serialize()
{
_serializer = new DataContractSerializer(typeof(UserSettingConfig));
}
public string SerializeObject(UserSettingConfig userSettingConfig)
{
using (var memoryStream = new MemoryStream())
{
_serializer.WriteObject(memoryStream, userSettingConfig);
string userSettingXml = memoryStream.ToString();
memoryStream.Close();
return userSettingXml;
}
}
public UserSettingConfig DeSerializeObject(string userSettingXml)
{
UserSettingConfig userSettingConfig;
using (var stream = new MemoryStream(userSettingXml))
{
stream.Position = 0;
userSettingConfig = (UserSettingConfig)_serializer.ReadObject(stream);
}
return userSettingConfig;
}
}
当内存流需要字节数组或int
时,这不起作用。我想我的Serialize返回一个字符串(我可以保存为varchar(MAX)在我的数据库)
DataContractSerializer.WriteObject
过载,占用XmlWriter
。您可以构造其中一个将XML写入StringBuilder
:
private static string SerializeToString(object objectToSerialize)
{
var serializer = new DataContractSerializer(objectToSerialize.GetType());
var output = new StringBuilder();
var xmlWriter = XmlWriter.Create(output);
serializer.WriteObject(xmlWriter, objectToSerialize);
xmlWriter.Close();
return output.ToString();
}
您也可以考虑序列化为JSON而不是XML,使用优秀的JSON。NET库,它可以很容易地序列化最复杂的对象。JSON非常紧凑,仍然可读。
序列化:
string json = Newtonsoft.Json.JavaScriptConvert.SerializeObject(anySerializableObject);
反序列化:MyClass instance = (MyClass) Newtonsoft.Json.JavaScriptConvert.DeserializeObject(json, typeof(MyClass));
如果需要xml而不需要xml声明,则应该使用XmlWriterSettings。例如,当您需要xml字符串的节点,而不是整个xml文档。
private static string SerializeToString(object objectToSerialize)
{
var serializer = new DataContractSerializer(objectToSerialize.GetType());
var output = new StringBuilder();
var xmlWriter = XmlWriter.Create(output, new XmlWriterSettings() { OmitXmlDeclaration = true});
serializer.WriteObject(xmlWriter, objectToSerialize);
xmlWriter.Close();
return output.ToString();
}