I have the following class to serialize
class Container
{
[JsonConverter(typeof(PropertyConverter))]
public PropertyBase SomeProperty { get; set; }
}
Which is serialized with
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
}:
var serialized = JsonConvert.SerializeObject(
new Container
{
SomeProperty = new PropertyImplementationA
{
PropertyA = "some string value"
}
}, settings);
but when I deserialize with
var deserialized = JsonConvert.DeserializeObject<Container>(settings);
The converter is not used.
On investigation, if I remove the sname case naming strategy it all works so it appears that Newtonsoft is registering the the converter to the property name with a different naming strategy when using the JsonConverterAttibute
.
Constraints
As a workaround one can register the converters with the serializer settings I won't always know the converters to be used when the settings are created, that isn't a feasable option for this case.
As another workaround one can decorate the properties with [JsonProperty("property_base")]
explicitly but this also isn't feasable as we would need to decorate properties all over the codebase.
This works as expected if one doesn't specify the SnameCaseNamingStrategy however this strategy is what the codebase already uses and can't be changed.
Question
How does one get the JsonConverterAttribute
to use the same naming strategy as the JsonSerializerSettings
passed to the JsonConvert.DeserializeObject
function?