序列化字典时保留大小写

Keep casing when serializing dictionaries(序列化字典时保留大小写)

本文介绍了序列化字典时保留大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样配置的 Web Api 项目:

I have a Web Api project being configured like this:

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

但是,我希望字典键的大小写保持不变.Newtonsoft.Json 中是否有任何属性可以用于一个类来表示我希望在序列化过程中大小写保持不变?

However, I want dictionary keys casing to remain unchanged. is there any attribute in Newtonsoft.Json I can use to a class to denote that I want casing to remain unchanged during serialization?

public class SomeViewModel
{
    public Dictionary<string, string> Data { get; set; }    
}

推荐答案

没有属性可以做到这一点,但是你可以通过自定义解析器来做到这一点.

There is not an attribute to do this, but you can do it by customizing the resolver.

我看到您已经在使用 CamelCasePropertyNamesContractResolver.如果您从中派生一个新的解析器类并覆盖 CreateDictionaryContract() 方法,则可以提供一个不会更改键名的替代 DictionaryKeyResolver 函数.

I see that you are already using a CamelCasePropertyNamesContractResolver. If you derive a new resolver class from that and override the CreateDictionaryContract() method, you can provide a substitute DictionaryKeyResolver function that does not change the key names.

这是您需要的代码:

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; }
}

这是上面的输出.请注意,所有类属性名称都是驼峰式大小写,但字典键保留了它们原来的大小写.

Here is the output from the above. Notice that all of the class property names are camel-cased, but the dictionary keys have retained their original casing.

{
  "anIntegerProperty": 42,
  "htmlString": "<html></html>",
  "dictionary": {
    "WHIZbang": "1",
    "FOO": "2",
    "Bar": "3"
  }
}

这篇关于序列化字典时保留大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:序列化字典时保留大小写

基础教程推荐