使用 DataContractSerializer 反序列化时出错
当我将对象反序列化回其原始类型时,我的对象始终为 null
。
这是我的代码:
ProjectSetup obj = new ProjectSetup();
if (System.Web.HttpContext.Current.Session["ProjectSetup"] == null)
setBookProjectSetup();
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
DataContractSerializer dcs = new DataContractSerializer(typeof(ProjectSetup));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(toDeserialise));
obj = (ProjectSetup) dcs.ReadObject(ms, true);
return obj;
When I am deserializing my object back to it's original type my object is always null
.
Here is my code:
ProjectSetup obj = new ProjectSetup();
if (System.Web.HttpContext.Current.Session["ProjectSetup"] == null)
setBookProjectSetup();
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
DataContractSerializer dcs = new DataContractSerializer(typeof(ProjectSetup));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(toDeserialise));
obj = (ProjectSetup) dcs.ReadObject(ms, true);
return obj;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设对
setBookProjectSetup
的调用将ProjectSetup
的实例放置在HttpSessionState
中,其键为ProjectSetup
代码>.这里的问题是这样开始的:
您随后使用 toDeserialize 字符串的内容作为反序列化的源。
除非您重载了
ToString
返回DataContractSerializer
将能够反序列化(这是极不可能的)您可能在Object< 上使用
ToString
的实现/code>,它只会返回类型的名称。然后,您尝试将该字符串反序列化到您的对象中,这是行不通的。
您需要做的是将对象正确序列化为字节数组/
MemoryStream
,如下所示:此时,
MemoryStream
将填充一系列表示序列化对象的字节。然后,您可以使用相同的 MemoryStream 取回对象:I'm going to assume that the call to
setBookProjectSetup
places an instance ofProjectSetup
in theHttpSessionState
with a key ofProjectSetup
.The issue here starts with this:
You subsequently use the contents of the
toDeserialize
string as the source of the deserialization.Unless you've overloaded
ToString
to return a byte stream that theDataContractSerializer
would be able to deserialize (it's highly unlikely) chances are you are using the implementation ofToString
onObject
, which will just return the type's name.Then, you are trying to deserialize that string into your object, which isn't going to work.
What you need to do is properly serialize your object into a byte array/
MemoryStream
, like so:At this point, the
MemoryStream
will be populated with a series of bytes representing your serialized object. You can then get the object back using the sameMemoryStream
: