用json.net反序列化用户列表

时间:2013-10-31 17:06:22

标签: json.net deserialization

你好,我有一个问题要反序列化这个json

{
    "166": {
        "uid": "166",
        "name": "test",
        "mail": "test@test.com"
    },
    "167": {
        "uid": "167",
        "name": "test",
        "mail": "test@test.com"
    },
    "168": {
        "uid": "168",
        "name": "test",
        "mail": "test@test.com"
    }
}

我使用json.net并将检索所有用户,但第一个元素总是更改其名称。

知道怎么治疗吗?

1 个答案:

答案 0 :(得分:1)

您可以通过反序列化为Dictionary<string, User>来处理这种情况,假设您的User类定义如下:

public class User
{
    public string uid { get; set; }
    public string name { get; set; }
    public string mail { get; set; }
}

这是一个演示:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""166"": {
                ""uid"": ""166"",
                ""name"": ""Joe"",
                ""mail"": ""joe@example.org""
            },
            ""167"": {
                ""uid"": ""167"",
                ""name"": ""Pete"",
                ""mail"": ""pete@example.org""
            },
            ""168"": {
                ""uid"": ""168"",
                ""name"": ""Fred"",
                ""mail"": ""fred@example.org""
            }
        }";

        Dictionary<string, User> users = 
            JsonConvert.DeserializeObject<Dictionary<string, User>>(json);

        foreach (KeyValuePair<string, User> kvp in users)
        {
            Console.WriteLine(kvp.Key);
            Console.WriteLine("  uid:  " + kvp.Value.uid);
            Console.WriteLine("  name: " + kvp.Value.name);
            Console.WriteLine("  mail: " + kvp.Value.mail);
        }
    }
}

这是输出:

166
  uid:  166
  name: Joe
  mail: joe@example.org
167
  uid:  167
  name: Pete
  mail: pete@example.org
168
  uid:  168
  name: Fred
  mail: fred@example.org