Getting error deserializing with DataContractSerializer
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;
I'm going to assume that the call to setBookProjectSetup
places an instance of ProjectSetup
in the HttpSessionState
with a key of ProjectSetup
.
The issue here starts with this:
string toDeserialise = System.Web.HttpContext.Current.
Session["ProjectSetup"].ToString();
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 the DataContractSerializer
would be able to deserialize (it's highly unlikely) chances are you are using the implementation of ToString
on Object
, 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:
using (var ms = new MemoryStream())
{
// Create the serializer.
var dcs = new DataContractSerializer(typeof(ProjectSetup));
// Serialize to the stream.
dcs.WriteObject(ms, System.Web.HttpContext.Current.Session["ProjectSetup"]);
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 same MemoryStream
:
// Reset the position of the stream so the read occurs in the right place.
ms.Position = 0;
// Read the object.
var obj = (ProjectSetup) dcs.ReadObject(ms);
}
精彩评论