Json.NET Dictionary with StringComparer serialization

后端 未结 3 1858
忘掉有多难
忘掉有多难 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

    Create an extension method which will copy the values from your case-sensitive dictionary to a new case-insensitive dictionary.

    public static Dictionary ToCaseInsensitive(this Dictionary caseSensitiveDictionary)
    {
        var caseInsensitiveDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase);
        caseSensitiveDictionary.Keys.ToList()
            .ForEach(k => caseInsensitiveDictionary[k] = caseSensitiveDictionary[k]);
    
        return caseInsensitiveDictionary;
    }
    

    Usage:

    var newDictionary = JsonConvert.DeserializeObject>(value)
    .ToCaseInsensitive();
    

    Although this works for me (and I like this solution due to its simplicity), please note the following caveats:

    • There is a minor overhead incurred ito the copying
    • If you have duplicate keys in the dictionary (such as "cat" and "CAT"), one will be overwritten. You can easily adapt the method to throw an exception in such cases (if you want).
    • My solution does not strictly use the comparer during deserialization, but is most probably the easiest way to get your dictionary into a case-insensitive state.

提交回复
热议问题