We have a situation where one on the fields that is being serialized and deserialized via json.net is a binding list property on one of our objects. when attempting to deserialize this field, we get an exception:
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Error resolving type specified in JSON 'WpfApplication1.Wrapper
1[[System.ComponentModel.BindingList
1[[System.String, mscorlib]], System]], WpfApplication1'. Path 'Potato.$type', line 4, position 131.
To reproduce, I've created a small sample:
public class ClassToSerialize
{
public Wrapper<BindingList<string>> Potato { get; set; }
}
public class Wrapper<T>
{
public Wrapper()
{
}
public Wrapper(T item)
{
Value = item;
}
#region Properties
[JsonProperty]
public T Value { get; set; }
#endregion
}
And the test is:
var objectToSerialize = new ClassToSerialize
{
Potato = new Wrapper<BindingList<string>>(new BindingList<string>
{
"tomato",
"basil"
})
};
string serializedPotato = JsonSerializer<ClassToSerialize>.Serialize(objectToSerialize, true);
ClassToSerialize deserializedPotato = JsonSerializer<ClassToSerialize>.Deserialize(serializedPotato);
Where the serialization code is simply:
public class JsonSerializer<T> where T : class
{
public static string Serialize(T item, bool isComplexType = false)
{
if (isComplexType)
{
string serializedJson = JsonConvert.SerializeObject(item, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
});
return serializedJson;
}
return JsonConvert.SerializeObject(item);
}
public static T Deserialize(string serializedItem)
{
var deserializedObject = JsonConvert.DeserializeObject<T>(serializedItem, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
return deserializedObject;
}
}
The error occurs here: ClassToSerialize deserializedPotato = JsonSerializer<ClassToSerialize>.Deserialize(serializedPotato);
but if I change the type of the underlying collection from BindingList<T>
to List<T>
, it all works fine.
Does anyone know what the problem here is and how to solve it?
Please note I've tested an unwrapped BindingList<>
(i.e. not wrapped in another type) and that works fine.
Many thanks,