将datacontract序列化对象保存为字符串以保存在sql db中

时间:2011-12-02 07:22:02

标签: c# sql xml

我有一个自定义类型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;
    }
}

这不起作用,因为Memory Stream想要一个字节数组或int

我希望我的Serialize返回一个字符串(我可以在我的数据库中保存为varchar(MAX))

3 个答案:

答案 0 :(得分:2)

DataContractSerializer.WriteObject的重载需要XmlWriter。您可以构建一个将XML写入StringBuilder

的XML
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();
}

答案 1 :(得分:1)

您还可以考虑使用优秀的JSON.NET库序列化为JSON而不是XML,它可以轻松地序列化最复杂的对象。 JSON非常紧凑,仍然可读。

序列化:

string json =  Newtonsoft.Json.JavaScriptConvert.SerializeObject(anySerializableObject);

要反序列化:

MyClass instance = (MyClass) Newtonsoft.Json.JavaScriptConvert.DeserializeObject(json, typeof(MyClass));

答案 2 :(得分:0)

如果你需要没有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();
}