如何反序列化JSON。我应该选择什么基类?

时间:2012-07-11 18:28:08

标签: c# json

如何将此JSON反序列化为

的实例

Dictionary<string, List<typeof(new {name=""; call=""})>>

列表中的类型不必是匿名的。

{ "item a": [ { "name": "alpha", "call": "a" } ],
  "item b": [],
  "item c": [ 
                   { "name" : "beta" , "call" : "b" }, 
                   { "name" : "gamma",  "call" : "g" },
                   { "name" : "alpha",  "call" : "a" }
                ]
    }

1 个答案:

答案 0 :(得分:2)

请勿使用匿名类型,请使用“真实”类型。 JSON.NET可以很好地反序列化它:

public class StackOverflow_11439028
{
    public class MyType
    {
        public string name { get; set; }
        public string call { get; set; }
    }

    const string Json = @"{ ""item a"": [ { ""name"": ""alpha"", ""call"": ""a"" } ],
                            ""item b"": [],
                            ""item c"": [ 
                                { ""name"" : ""beta"" , ""call"" : ""b"" }, 
                                { ""name"" : ""gamma"",  ""call"" : ""g"" },
                                { ""name"" : ""alpha"",  ""call"" : ""a"" }
                            ]
                        }";

    public static void Test()
    {
        JsonSerializer js = new JsonSerializer();
        Func<List<MyType>, string> listToString = l =>
            "[" + string.Join(", ", l.Select(t => string.Format("{0}-{1}", t.call, t.name))) + "]";

        using (JsonTextReader jtr = new JsonTextReader(new StringReader(Json)))
        {
            var obj = js.Deserialize<Dictionary<string, List<MyType>>>(jtr);
            Console.WriteLine(string.Join(", ", obj.Select(kvp => string.Format("{{{0}, {1}}}", kvp.Key, listToString(kvp.Value)))));
        }

        JavaScriptSerializer jss = new JavaScriptSerializer();
        var dict = jss.Deserialize<Dictionary<string, List<MyType>>>(Json);
        Console.WriteLine(string.Join(", ", dict.Select(kvp => string.Format("{{{0}, {1}}}", kvp.Key, listToString(kvp.Value)))));
    }
}