gpt4 book ai didi

c# - 使用DataContractSerializer序列化,反序列化不回来

转载 作者:IT王子 更新时间:2023-10-29 03:44:13 24 4
gpt4 key购买 nike

我有以下两个功能:

public static string Serialize(object obj)
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, obj);
return Encoding.UTF8.GetString(memoryStream.GetBuffer());
}

public static object Deserialize(string xml, Type toType)
{
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
// memoryStream.Position = 0L;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
DataContractSerializer dataContractSerializer = new DataContractSerializer(toType);
return dataContractSerializer.ReadObject(reader);
}

第一个似乎可以很好地将对象序列化为 xml 字符串。 XML 看起来有效,没有损坏的标签,开头或结尾没有空格等。现在第二个函数不想将我的 xml 字符串反序列化回对象。在最后一行我得到:

There was an error deserializing the object of type [MY OBJECT TYPE HERE]. The data at the root level is invalid. Line 1, position 1.

我做错了什么?我试过几次重写 Deserialize 函数,似乎总是同一种错误。谢谢!

哦,这就是我调用这 2 个函数的方式:

SomeObject so = new SomeObject();
string temp = SerializationManager.Serialize(so);
so = (SomeObject)SerializationManager.Deserialize(temp, typeof(SomeObject));

最佳答案

这是我一直以来的做法:

    public static string Serialize(object obj) {
using(MemoryStream memoryStream = new MemoryStream())
using(StreamReader reader = new StreamReader(memoryStream)) {
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
return reader.ReadToEnd();
}
}

public static object Deserialize(string xml, Type toType) {
using(Stream stream = new MemoryStream()) {
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
stream.Write(data, 0, data.Length);
stream.Position = 0;
DataContractSerializer deserializer = new DataContractSerializer(toType);
return deserializer.ReadObject(stream);
}
}

关于c# - 使用DataContractSerializer序列化,反序列化不回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5010191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com