Json.NET Dictionary with StringComparer serialization

后端 未结 3 1859
忘掉有多难
忘掉有多难 2020-12-16 11:30

I have a dictionary Dictionary>. Both the outer dictionary and the inner one have an equality comparer set(in my

3条回答
  •  醉酒成梦
    2020-12-16 12:07

    One simple idea would be to create a subclass of Dictionary that sets the comparer to StringComparer.OrdinalIgnoreCase by default, then deserialize into that instead of the normal dictionary. For example:

    class CaseInsensitiveDictionary : Dictionary
    {
        public CaseInsensitiveDictionary() : base(StringComparer.OrdinalIgnoreCase)
        {
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"
            {
                ""Foo"" : 
                {
                    ""fiZZ"" : 1,
                    ""BUzz"" : ""yo""
                },
                ""BAR"" :
                {
                    ""dIt"" : 3.14,
                    ""DaH"" : true
                }
            }";
    
            var dict = JsonConvert.DeserializeObject>>(json);
    
            Console.WriteLine(dict["foo"]["fizz"]);
            Console.WriteLine(dict["foo"]["buzz"]);
            Console.WriteLine(dict["bar"]["dit"]);
            Console.WriteLine(dict["bar"]["dah"]);
        }
    }
    

    Output:

    1
    yo
    3.14
    True
    

提交回复
热议问题