Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Work-Around for DataContractJsonSerializer ArgumentNullExceptions

0.00/5 (No votes)
24 Oct 2010 1  
Stop trailling nulls from preventing deserialization.
If you've tried using a DataContractJsonSerializer or a DataContractSerializer with Push Notification for the Windows Phone, you may have experienced an ArgumentNullException during deserialization. This can happen because the MemoryStream is buffered with null characters '\0' that prevent deserialization. A solution is to create a new array and copy all bytes except for the trailing nulls, as shown in the following excerpt:

using (BinaryReader reader = new BinaryReader(bodyStream))
{
	byte[] bodyBytes = reader.ReadBytes((int)bodyStream.Length);

	int lengthWithoutNulls = bodyBytes.Length;
	for (int i = bodyBytes.Length - 1; i >= 0 && bodyBytes[i] == '\0'; 
			i--, lengthWithoutNulls--)
	{
		/* Intentionally left blank. */
	}
 
	byte[] cleanedBytes = new byte[lengthWithoutNulls];
	Array.Copy(bodyBytes, cleanedBytes, lengthWithoutNulls);
 
	DataContractJsonSerializer serializer
		= new DataContractJsonSerializer(typeof(StockQuote));
 
	using (MemoryStream stream = new MemoryStream(cleanedBytes))
	{
		StockQuote = (StockQuote)serializer.ReadObject(stream);
	}
}


This excerpt is from the downloadable sample code in my upcoming book Windows Phone 7 Unleashed.


Have a great day!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here