0

我怎么能把这个 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" }
                ]
    }
4

1 回答 1

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)))));
    }
}
于 2012-07-11T18:33:41.083 回答