Il n'y a pas d'attribut pour faire cela, mais vous pouvez le faire en personnalisant le résolveur.
Je vois que vous utilisez déjà un fichier CamelCasePropertyNamesContractResolver. Si vous dérivez une nouvelle classe de résolveur à partir de cela et remplacez la CreateDictionaryContract()méthode, vous pouvez fournir une DictionaryKeyResolverfonction de remplacement qui ne modifie pas les noms de clé.
Voici le code dont vous auriez besoin:
class CamelCaseExceptDictionaryKeysResolver : CamelCasePropertyNamesContractResolver
{
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
JsonDictionaryContract contract = base.CreateDictionaryContract(objectType);
contract.DictionaryKeyResolver = propertyName => propertyName;
return contract;
}
}
Démo:
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo
{
AnIntegerProperty = 42,
HTMLString = "<html></html>",
Dictionary = new Dictionary<string, string>
{
{ "WHIZbang", "1" },
{ "FOO", "2" },
{ "Bar", "3" },
}
};
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new CamelCaseExceptDictionaryKeysResolver(),
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(foo, settings);
Console.WriteLine(json);
}
}
class Foo
{
public int AnIntegerProperty { get; set; }
public string HTMLString { get; set; }
public Dictionary<string, string> Dictionary { get; set; }
}
Voici la sortie de ce qui précède. Notez que tous les noms de propriété de classe sont en camel, mais les clés du dictionnaire ont conservé leur casse d'origine.
{
"anIntegerProperty": 42,
"htmlString": "<html></html>",
"dictionary": {
"WHIZbang": "1",
"FOO": "2",
"Bar": "3"
}
}