I'm trying to (de)serialize a class with this simple piece of code:-
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
// Serialize
var json = JsonConvert.SerializeObject(obj, settings);
// Deseralize - this is where it fails
var test = JsonConvert.DeserializeObject<MyObject>(json, settings);
DeseralizeObject() fails with a JsonSerializationException:-
Error resolving type specified in JSON 'Xxx.Common.MyObject, Xxx.Common'. Path '$type', line 1, position 110
Inner exception: JsonSerializationException, message "Could not load assembly 'Xxx.Common".
I don't understand why it can't load the assembly - it's being referenced by this project!
It works if I don't use the JsonSerializerSettings
, however I need this because the class being serialized will eventually have a List<SomeBaseClass>
property that will contain derived types.
Any thoughts? I'm using Json.Net v6.0.
Edit:
I just tried adding TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
to my serializer settings, which resulted in this different (and confusing) exception message:-
Type specified in JSON 'Xxx.Common.MyObject, Xxx.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not compatible with 'Xxx.Common.MyObject, Xxx.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Path '$type', line 1, position 165.
Edit2:
To clarify things, the above code is a complete repro of the problem, and resides in a larger WPF application, while MyObject
resides in a different project ("Xxx.Common") in the same solution, and is referenced by the WPF application project - I've simply replaced our company namespace with "Xxx" for this post.
MyObject is a simple POCO that I've created to rule out any issues that may be due to complex types, and consists of a few string and double properties, i.e.
public class MyObject
{
public string Name {get;set;}
public double Foo {get;set;}
...
}
The serialized JSON looks like this (again company NS replaced) - the pertinent part (i.e. the "$type") appears to be correct:-
{"$type":"Xxx.Common.MyObject, Xxx.Common","Name":null,"Foo":0.0,"StepSize":0.0,"Convergence":0.0,"Cutoff":0.0}