zeng ande

asp.net core 序列化字典时保留 key 的大小写

重写 CamelCasePropertyNamesContractResolver 的 CreateDictionaryContract 方法

stackoverflow

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 就会保留大小写

posted @ 2021-03-03 14:52  zengande  阅读(198)  评论(0编辑  收藏  举报