如何反序列化具有动态(数字)键名的子对象
本文关键字:对象 数字 反序列化 动态 | 更新日期: 2023-09-27 18:13:03
我如何反序列化这个JSON数据?键"100034"等在本质上是动态的。
{
"users" : {
"100034" : {
"name" : "tom",
"state" : "WA",
"id" : "cedf-c56f-18a4-4b1"
},
"10045" : {
"name" : "steve",
"state" : "NY",
"id" : "ebb2-92bf-3062-7774"
},
"12345" : {
"name" : "mike",
"state" : "MA",
"id" : "fb60-b34f-6dc8-aaf7"
}
}
}
是否有一种方法可以直接访问具有名称,状态和Id的每个对象?
对于具有可变属性名的JSON对象,您可以使用Dictionary<string, T>
代替常规类,其中T
是表示项数据的类。
这样声明你的类:
class RootObject
{
public Dictionary<string, User> users { get; set; }
}
class User
{
public string name { get; set; }
public string state { get; set; }
public string id { get; set; }
}
然后这样反序列化:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
演示:class Program
{
static void Main(string[] args)
{
string json = @"
{
""users"": {
""10045"": {
""name"": ""steve"",
""state"": ""NY"",
""id"": ""ebb2-92bf-3062-7774""
},
""12345"": {
""name"": ""mike"",
""state"": ""MA"",
""id"": ""fb60-b34f-6dc8-aaf7""
},
""100034"": {
""name"": ""tom"",
""state"": ""WA"",
""id"": ""cedf-c56f-18a4-4b1""
}
}
}";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (string key in root.users.Keys)
{
Console.WriteLine("key: " + key);
User user = root.users[key];
Console.WriteLine("name: " + user.name);
Console.WriteLine("state: " + user.state);
Console.WriteLine("id: " + user.id);
Console.WriteLine();
}
}
}
输出:key: 10045
name: steve
state: NY
id: ebb2-92bf-3062-7774
key: 12345
name: mike
state: MA
id: fb60-b34f-6dc8-aaf7
key: 100034
name: tom
state: WA
id: cedf-c56f-18a4-4b1
-
添加package System.Web.Script.Serialization;
-
假设您的JSON包含Internet用户列表,我创建一个这样的类。
public class internet { public List<User> Users { get; set; } }; public class User { public String Name { get; set; } public String Id { get; set; } public String State { get; set; } };
假设你的JSON字符串在变量'JSONDATA'中,按照下面的代码将JSON数据DE序列化到Class对象。
var JSONDATA = /* Your JSON String */;
JavaScriptSerializer serializer = new JavaScriptSerializer();
internet Intr = serializer.Deserialize<internet>(JSONDATA);