I have a problem when I attempt to use JSON.net
to serialize my custom data class - properties of primitive types are serialized correctly, but properties which are classes themselves will just be serialized as string (full type name and nothing else, no actual values).
The class types are loaded dynamically with Assembly.LoadFrom(file)
, and the property types are then decorated with TypeDescriptor.AddAttributes
to add ExpandableObjectConverter
- this allows WinForms Property Grid
control to expand them and set their inner values.
The problem here is indeed the TypeConverter[typeof(ExpandableObjectConverter)]
. JSON.Net's DefaultContractResolver will retrieve the type converter and call CanConvertTo(typeof(string)) which will return true, and therefore it will use a StringContract for that type - it will be serialized as a string.
First solution is from JSON.Net side - implement your own ContractResolver as described here. Then you can override CreateContract like this and always feed correct Contract for your types decorated with the TypeConverter attribute:
protected override JsonContract CreateContract(Type objectType)
{
if (TypeDescriptor.GetAttributes(objectType).Contains(new TypeConverterAttribute(typeof(ExpandableObjectConverter))))
{
return this.CreateObjectContract(objectType);
}
return base.CreateContract(objectType);
}
Second solution is to make your own ExpandableObjectConverter, and override its CanConvertTo method to return false for string - this is what JSON.Net calls and will therefore not consider it to be StringContract, and will fall back to ObjectContract.