问题 xml 反序列化递归嵌套对象
已解决:下面的代码不会像我想象的那样导致无限循环。循环位于调用反序列化的代码中。这个发布的代码工作得很好
我正在尝试将以下对象序列化和反序列化为 xml
public class MessageObjectCollection : List<MessageObject>
{
public string Serialize()
{
return XmlObjectSerializer.SerializeObject(this);
}
public static MessageObjectCollection DeSerialize(string serializedPriceHistory)
{
return XmlObjectSerializer.DeserializeObject<MessageObjectCollection>(serializedPriceHistory);
}
}
MessageObject 类看起来像这样
public class MessageObject
{
public string Title;
public MessageObjectCollection Responses;
}
所以如果我有一个如下所示的 messageobjectcollection 实例:
var msgColl = new MessageObjectCollection
{
new MessageObject
{
Title = "Hello",
Responses = new MessageObjectCollection
{
new MessageObject
{
Title = "hi",
Responses = null
}
}
}
}
我可以通过调用来序列化它 var xml = msgColl.Serialize();
但是,当我尝试通过调用反序列化它时 var msgColl = new MessageObjectCollection().Deserialize(xml);
我在反序列化方法中遇到堆栈溢出异常:
public static T DeserializeObject<T>(string xml)
{
T result;
var ser = new XmlSerializer(typeof(T));
var buffer = StringToUTF8ByteArray(xml);
using (var stream = new MemoryStream(buffer, 0, buffer.Length))
{
result = (T) ser.Deserialize(stream);
}
return result;
}
有人知道我做错了什么吗?
Solved: code below is not causing an infinite loop as I thought. the loop was in the code calling the deserialization. this posted code works just fine
I am trying to serialize and deserialize to xml the following object
public class MessageObjectCollection : List<MessageObject>
{
public string Serialize()
{
return XmlObjectSerializer.SerializeObject(this);
}
public static MessageObjectCollection DeSerialize(string serializedPriceHistory)
{
return XmlObjectSerializer.DeserializeObject<MessageObjectCollection>(serializedPriceHistory);
}
}
The MessageObject class looks like this
public class MessageObject
{
public string Title;
public MessageObjectCollection Responses;
}
So if I have a instance of messageobjectcollection that looks like:
var msgColl = new MessageObjectCollection
{
new MessageObject
{
Title = "Hello",
Responses = new MessageObjectCollection
{
new MessageObject
{
Title = "hi",
Responses = null
}
}
}
}
I can serialize this just fine by calling
var xml = msgColl.Serialize();
However when I try to deserialize this by calling
var msgColl = new MessageObjectCollection().Deserialize(xml);
I get an stack overflow exception in the deserialization method:
public static T DeserializeObject<T>(string xml)
{
T result;
var ser = new XmlSerializer(typeof(T));
var buffer = StringToUTF8ByteArray(xml);
using (var stream = new MemoryStream(buffer, 0, buffer.Length))
{
result = (T) ser.Deserialize(stream);
}
return result;
}
Anyone know what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定它是否与问题相关,但由于反序列化方法是静态的,您不应该调用...
而不是...
??
Im not sure if its relevant to the problem but as the Deserialize method is static shouldn't you be calling...
instead of...
??