你好,我在反序列化这个 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 并会检索所有用户,但第一个元素总是更改其名称。
知道如何治疗它吗?
你可以
通过反序列化为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