I have the following code which is part of unit testing for serialization support in my API:
private void TestGraphSerializationJson(IGraph g)
{
StringWriter writer = new StringWriter();
JsonSerializer serializer = new JsonSerializer();
//The following line should make the serializer output type names
//in the JSON but seems to be ignored
serializer.TypeNameHandling = TypeNameHandling.All;
serializer.Serialize(new JsonTextWriter(writer), g);
Console.WriteLine("Serialized Form:");
Console.WriteLine(writer.ToString());
Console.WriteLine();
Object h = serializer.Deserialize<Graph>(new JsonTextReader(new StringReader(writer.ToString())));// as Graph;
Console.WriteLine(h.GetType().FullName);
Assert.AreEqual(g, h, "Graphs should be equal");
}
Various classes in my API implement the ISerializable interface and Json.Net quite happily serializes my classes into appropriate JSON.
The problem is that when I try and deserialize my object I get a fairly epic stack trace and the following error message:
Test method VDS.RDF.Test.Writing.Serialization.GraphSerializationTests.SerializationJsonGraph threw exception: Newtonsoft.Json.JsonSerializationException: ISerializable type ‘VDS.RDF.INode’ does not have a valid constructor..
Now the problem seems to be that Json.Net is trying to use ISerializable but that the particular objects I’m deserializing are typed as interfaces so it is trying to instantiate the interface rather than the actual implementations of that interface that were originally serialized.
So investigating further I saw that the Json.Net provides a TypeNameHandling setting on the serializer which can be used to include type names. So I set this to All as you can see in the code snippet but this does not seem to have any effect. The only types that gets type names inserted are List<T> types which is no help to me and still leaves me with the same frustrating error message.
Have I done something wrong here or is there a bug with Json.Net and the TypeNameHandling setting?
For the record I am using the latest Json.Net release albeit the .Net 3.5 build
This actually appears to be bug in Json.Net after further investigation.
I have posted this along with a more minimal test case and patch that fixes the issue at http://json.codeplex.com/workitem/21215