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?
It seems that ContractResolver gives a priority to a JsonConverter. I think maybe it is a good idea otherwise it would be hard to predict a result. If you move a contract resolver into a JsonConverter or add the property names explicitly everyting is ok
Everything is working fine when I added contract resolver settings inside of the json converter. In this case you don't need JsonProperty attributes. I also made the converter much more simple
and classes could be much more simple too
and even more simple , you can use SerializeTypeNameHandling option of Newtonsoft.Json https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm