Problems with Silverlight DataContractJsonSerializer.
I don’t think I am a patient developer, I do know good developers and they are very patient people that will discover the issues and find what’s the best solution. I write code fast and I expect everything to work, I spend my time in design so if something that I didn’t anticipate does not work for an unknown limitation, I get very frustrated. Last week I had to use the DataContractJsonSerializer. No problem I thought as I have used before the XML serializer.
For the Silverlight communication this is the class you want to use.
The class is on the namespace:
using System.Runtime.Serialization.Json;
Yet make sure the System.ServiceModel.Web.dll is referenced. This would be my first question.
Using primitive objects for some reason that I haven’t discovered yet gives me this exception below:
Testing' is not a valid JSON primitive. This error can also occur when extraneous data is present after the JSON data."
string obj = "test"; MemoryStream memoryStream = new MemoryStream(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); serializer.WriteObject(memoryStream, obj); memoryStream.Position = 0; StreamReader streamReader = new StreamReader(memoryStream); string JSON = streamReader.ReadToEnd(); memoryStream.Close();
Now using generics I get this exception for some another weird reason:
System.MissingMethodException was unhandled by user code
Message="Method not found: 'Boolean System.Runtime.Serialization.DataContract.get_IsReference()'."
Source="System.ServiceModel.Web"
Looking at the web, I found many other people with issues using that class. I should spend some time this weekend and debug that class to see what the problems might be or if I’m misusing it, yet I accomplish to get it working for now. After the projects that I am in a rush to finish, I promise I’ll go back and debug it to find where those exceptions.
Thanks Richie Carmichael for sending me a sample of a good use for the class.
Those are links from the forums with similar issues with the DataContractJsonSerializer class:
http://pietschsoft.com/post/2008/08/NET-35-SP1-DataContractJsonSerializer-Bug.aspx



Comments
Morten said on 3.18.2009 at 11:40 PM
Also note that if you try to deserialize more than 2mb of JSON data you will get a similar exception, unless you change the MaxLength property.
Efim said on 5.14.2009 at 2:46 PM
You have to use the [DataContract] and [DataMember] attributes on your data:
[DataContract]
public class MyData
{
public MyData()
{
this.Children = new List<MyData>();
}
[DataMember]
public string Name { get; set; }
[DataMember]
public string Value { get; set; }
[DataMember]
public List<MyData> Children { get; set; }
}