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--)
{
}
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!
Daniel is a former senior engineer in Technology and Research at the Office of the CTO at Microsoft, working on next generation systems.
Previously Daniel was a nine-time Microsoft MVP and co-founder of
Outcoder, a Swiss software and consulting company.
Daniel is the author of Windows Phone 8 Unleashed and Windows Phone 7.5 Unleashed, both published by SAMS.
Daniel is the developer behind several acclaimed mobile apps including
Surfy Browser for Android and Windows Phone. Daniel is the creator of a number of popular open-source projects, most notably
Codon.
Would you like Daniel to bring value to your organisation?
Please contact
Blog |
Twitter
Xamarin Experts
Windows 10 Experts