I am trying to write a custom contract resolver that extends DefaultContractResolver in Newtonsoft.Json.Serialization, with the goal of converting all properties within an ExpandoObject to have PascalCase property names.
My contract:
public class Fruit
{
public int Id { get; set; }
public ExpandoObject FruitProperties { get; set; }
}
I am passing in the following data:
{
"Id": "1234",
"FruitProperties" : {
"colour": "red",
"Taste": "sweet
}
}
}
The result I am expecting is the following:
{
"Id": "1234",
"FruitProperties" : {
"Colour": "red",
"Taste": "sweet"
}
}
I have tried overriding ResolvePropertyName, and CreateProperty methods in the DefaultContractResolver with no luck. All of these skip the sub properties within the expando object. Does anyone know what method in the DefaultContractResolver I need to override to convert the sub property names in the Expando to PascalCase?
ExpandoObject
isn't serialized through reflection so modifyingCreateProperty
won't work. Rather, it is serialized as anIDictionary<string, object>
. Thus you can take advantage of the newNamingStrategy
type in Json.NET 9.0.1 to create a custom naming strategy to PascalCase only dictionary keys and nothing else.NamingStrategy
has a propertyNamingStrategy.ProcessDictionaryKeys
that, when set totrue
, causes Json.NET to map dictionary key names:Then set it on
DefaultContractResolver.NamingStrategy
(or on any custom subclass ofDefaultContractResolver
if you prefer):Which outputs: