Deserialize json array of dictionaries in c#

后端 未结 2 2084
梦毁少年i
梦毁少年i 2021-01-05 00:31

I have an array of dictionaries that I\'ve created in javascript. After serializing to json I get the following string :

\"[{\\\"key\\\":\\\"60236\\\",\\\"va         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-05 01:25

    There are several ways that you can extract your key/value pairs to construct a dictionary:

    var dict = "[{\"key\":\"60236\",\"value\":\"1\"},  
                 {\"key\":\"60235\",\"value\":\"gdsfgdfsg\"},
                 {\"key\":\"60237\",\"value\":\"1\"}]";
    

    Use List>

    var dictionary = JsonConvert.DeserializeObject>>(dict)
                                     .ToDictionary(x => x.Key, y => y.Value);
    

    Use a custom object that represents your pairs and then create a dictionary from your collection.

    var output = JsonConvert.DeserializeObject>(dict);
    var dictionary = output.ToDictionary(x => x.Key, y => y.Value);
    
    public class Temp
    {
        public int Key { get; set; }
        public string Value { get; set; }
    }
    

    Finally, if you're uncomfortable with using a custom "throwaway" object just for deserialization, you can take a tiny performance hit and use dynamic instead.

    var dictionary = JsonConvert.DeserializeObject>(dict)
                                     .ToDictionary (x => (int)x.key, y => (string)y.value);
    

提交回复
热议问题