0

你好我有一个反序列化这个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 并会检索所有用户,但第一个元素总是更改其名称。

知道如何治疗吗?

4

1 回答 1

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
于 2013-10-31T22:38:39.987 回答