-1

我知道这个问题被问得令人作呕,但现有的答案对我来说并不是特别有帮助。最好的是将JSON 反序列化为 C# 动态对象?,但我不想创建一个对象,我想创建一个字典。

我像这样序列化我的数据,并且我想反序列化为完全相同的数据结构:

    public static string AugDictToJSON(Dictionary<string, List<Dictionary<string, object>>> dict)
    {
        return string.Join(",", dict.Select(
            d => string.Format("{{ \"{0}\" : [ {1} ] }}", d.Key,
                string.Join(",", d.Value.Select(i => SubAugDictToJSON(i)).ToArray())
            )).ToArray());
    }

    public static string SubAugDictToJSON(Dictionary<string, object> dict)
    {
        return string.Join(",", dict.Select(
                d => string.Format("{{ \"{0}\" : \"{1}\" }}", d.Key, d.Value.ToString())
            ).ToArray());
    }

编辑:解决方案如下(来自接受的答案):

public static Dictionary<string, List<Dictionary<string, object>>> JSONToAugDict(string json)
{
    return JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, object>>>>(json);
}
4

2 回答 2

3

我建议使用 NuGet 包“ Newtonsoft.Json ”。

WebAPI 使用此包进行序列化/反序列化,速度非常快。更多信息可以在这里找到:http: //james.newtonking.com/pages/json-net.aspx

var results = JsonConvert.DeserializeObject<dynamic>(json);

或者,作为一个字典:

var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(json);
于 2012-10-01T17:15:13.787 回答
1

我尝试使用 Json.NET 为我正在开发的应用程序进行类似的操作(取自我自己的问题:将 json 字符串反序列化为对象 - Silverlight

JSON

{
    "disclaimer": "This data is collected from various providers and provided free of charge for informational purposes only, with no guarantee whatsoever of accuracy, validity, availability or fitness for any purpose; use at your own risk. Other than that - have fun, and please share/watch/fork if you think data like this should be free!",
    "license": "Data collected from various providers with public-facing APIs; copyright may apply; not for resale; no warranties given.",
    "timestamp": 1334183999,
    "base": "USD",
    "rates": {
                "AED": 3.6732,
                "AFN": 48.400002,
                "ALL": 106.669998,
             }
}

将保存数据的对象:

public class ExchangeData
{
    public string disclaimer { get; set; }
    public string license { get; set; }
    public string timestamp { get; set; }
    public string @base { get; set; }
    public Dictionary<string, double> rates { get; set; }
}

创建数据结构:

StreamReader reader = new StreamReader(args.Result);
ExchangeData data = JsonConvert.DeserializeObject<ExchangeData>(reader.ReadToEnd());

希望能帮助到你!

于 2012-10-01T17:44:49.513 回答