Json.NET字典< string,T>与StringComparer序列化 [英] Json.NET Dictionary<string,T> with StringComparer serialization

查看:59
本文介绍了Json.NET字典< string,T>与StringComparer序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字典Dictionary<string, Dictionary<string, object>>.外部词典和内部词典都具有一个相等比较器集(在我的情况下是StringComparer.OrdinalIgnoreCase).在字典进行序列化和反序列化之后,两个字典的比较器都未设置为StringComparer.OrdinalIgnoreCase.

I have a dictionary Dictionary<string, Dictionary<string, object>>. Both the outer dictionary and the inner one have an equality comparer set(in my case it is StringComparer.OrdinalIgnoreCase). After the dictionary is serialized and deserialized the comparer for both dictionaries is not set to StringComparer.OrdinalIgnoreCase.

如果您可以控制代码中字典的创建,则可以创建一个从字典继承的类,并在该类的默认构造函数中设置比较器.但是,如果您无法控制字典的创建并从其他代码中获取字典,该怎么办?

If you have control over the creation of the dictionaries in your code, you can create a class inherited from the dictionary and set comparer in the default constructor of the class. But what if you do not have control over dictionary creation and you get the dictionary from the other code?

有什么方法可以使用比较器正确地对其进行序列化/反序列化吗?

Is there any way to serialize/deserialize it correctly with the comparer?

推荐答案

一个简单的想法是创建Dictionary<string, string>的子类,该子类默认情况下将比较器设置为StringComparer.OrdinalIgnoreCase,然后反序列化为该类,而不是普通的字典.例如:

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

class CaseInsensitiveDictionary<V> : Dictionary<string, V>
{
    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<CaseInsensitiveDictionary<CaseInsensitiveDictionary<object>>>(json);

        Console.WriteLine(dict["foo"]["fizz"]);
        Console.WriteLine(dict["foo"]["buzz"]);
        Console.WriteLine(dict["bar"]["dit"]);
        Console.WriteLine(dict["bar"]["dah"]);
    }
}

输出:

1
yo
3.14
True

这篇关于Json.NET字典&lt; string,T&gt;与StringComparer序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆