Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - Json.NET Dictionary<string,T> with StringComparer serialization

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"]);
    }
}

Output:

1
yo
3.14
True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...