asp.net core 序列化字典时保留 key 的大小写
重写 CamelCasePropertyNamesContractResolver 的 CreateDictionaryContract 方法
public class CamelCaseExceptDictionaryKeysResolver : CamelCasePropertyNamesContractResolver
{
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
JsonDictionaryContract contract = base.CreateDictionaryContract(objectType);
contract.DictionaryKeyResolver = propertyName => propertyName;
return contract;
}
}
在 Startup 添加 MVC Json 配置
service.AddMvc()
.AddNewtonsoftJson(options => {
options.SerializerSettings.ContractResolver = new CamelCaseExceptDictionaryKeysResolver();
});
这样序列化字典输出的 key 就会保留大小写