反序列化在C#中词典JSON数组 [英] Deserialize json array of dictionaries in c#

查看:276
本文介绍了反序列化在C#中词典JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我已经在JavaScript创建字典的数组。经过序列化到JSON我得到以下字符串:

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

"[{\"key\":\"60236\",\"value\":\"1\"},{\"key\":\"60235\",\"value\":\"gdsfgdfsg\"},{\"key\":\"60237\",\"value\":\"1\"}]"

我有一个很难得到这种反序列化到C#或者列表或字典。

I am having a hard time getting this deserialized into either a list or dictionary in c#.

我试过:

Dictionary<int, string> values = JsonConvert.DeserializeObject<Dictionary<int, string>>(Model.Json);



但是,这并不正常工作。

but that doesn't work.

推荐答案

有几种方法,你可以提取您的键/值对构建词典:

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

使用列表< KeyValuePair< INT,串>>

var dictionary = JsonConvert.DeserializeObject<List<KeyValuePair<int, string>>>(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<List<Temp>>(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<List<dynamic>>(dict)
                                 .ToDictionary (x => (int)x.key, y => (string)y.value);

这篇关于反序列化在C#中词典JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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