Using JavaScriptSerializer.DeserializeObject how can I get back a Dictionary that uses a case insensitive string comparer?

[亡魂溺海] 提交于 2019-12-04 19:57:36

问题


I have some JSON that I need to deserialize so I'm using JavaScriptSerializer.DeserializeObject like:

var jsonObject = serializer.DeserializeObject(line) as Dictionary<string, object>;

The problem is that the Dictionary that comes back has a case-sensitive key comparer, but I need case-insensitive. Is there some way to get back a Dictionary that is case-insensitive?

EDIT: I'd prefer not to copy the data to a new structure, since I have a lot of data and this will be costly.


回答1:


Just create a new case insensitive dictionary and populate it with the current one.

var jsonObject = serializer.DeserializeObject(line) as Dictionary<string, object>;
var caseInsensitiveDictionary = new Dictionary<string, object>(jsonObject, StringComparer.OrdinalIgnoreCase);

[UPDATE] Test code:

    Stopwatch stop1 = new Stopwatch();
    Stopwatch stop2 = new Stopwatch();

    //do test 100 000 times
    for (int j = 0; j < 100000; j++)
    {
        //generate fake data
        //object with 50 properties
        StringBuilder json = new StringBuilder();
        json.Append('{');
        for (int i = 0; i < 100; i++)
        {
            json.Append(String.Format("prop{0}:'val{0}',", i));
        }
        json.Length = json.Length - 1;
        json.Append('}');

        var line = json.ToString();

        stop1.Start();
        var serializer = new JavaScriptSerializer();
        var jsonObject = serializer.DeserializeObject(line) as Dictionary<string, object>;
        stop1.Stop();

        stop2.Start();
        var caseInsensitiveDictionary = new Dictionary<string, object>(jsonObject, StringComparer.OrdinalIgnoreCase);
        stop2.Stop();
    }

    Console.WriteLine(stop1.Elapsed);
    Console.WriteLine(stop2.Elapsed);
    Console.Read();

The result is:

Deserializtion time: 1 min 21 sec

Dictionary creation time: 3 sec

So, the main proble is deserializtion. Dictionary creation is about 4%




回答2:


I would recommend creating a new class that inherits from Dictionary<string, object> and in the constructor of this class, assign the case-insensitive comparer. I don't think it can be serialized to and from JSON.



来源:https://stackoverflow.com/questions/8350169/using-javascriptserializer-deserializeobject-how-can-i-get-back-a-dictionary-tha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!