在C#中反序列化JSON

时间:2012-10-01 17:08:35

标签: c# javascript .net json

我知道这个问题已被问到令人作呕,但现有的答案对我来说并不是特别有帮助。最好的是Deserialize JSON into C# dynamic object?,但我不想创建一个对象,我想创建一个Dictionary。

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

    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);
}

2 个答案:

答案 0 :(得分:3)

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

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

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

或者,作为IDictionary:

var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(json);

答案 1 :(得分:1)

我尝试使用Json.NET类似于我正在处理的应用程序(取自我自己的问题:Deserializing json string into an object - 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());

希望它有所帮助!