これを行うための属性はありませんが、リゾルバーをカスタマイズすることで実行できます。
すでにを使用しているようCamelCasePropertyNamesContractResolverです。それから新しいリゾルバークラスを派生させてCreateDictionaryContract()メソッドをオーバーライドする場合は、代替を提供できますDictionaryKeyResolverキー名を変更しない関数を。
必要なコードは次のとおりです。
class CamelCaseExceptDictionaryKeysResolver : CamelCasePropertyNamesContractResolver
{
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
JsonDictionaryContract contract = base.CreateDictionaryContract(objectType);
contract.DictionaryKeyResolver = propertyName => propertyName;
return contract;
}
}
デモ:
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; }
}
上記の出力は次のとおりです。すべてのクラスプロパティ名はキャメルケースになっていますが、ディクショナリキーは元の大文字小文字を保持していることに注意してください。
{
"anIntegerProperty": 42,
"htmlString": "<html></html>",
"dictionary": {
"WHIZbang": "1",
"FOO": "2",
"Bar": "3"
}
}