使用不同的键名称序列化 JSON 数据给反序列化带来了挑战。本文探讨了在 C# 中使用动态属性模式的解决方案。
考虑下面的 JSON 数据,我们如何在维护动态“数字”键的同时反序列化它?
{ "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" } } }
动态属性模式
我们可以使用字典
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; } }
反序列化
要使用动态属性模式反序列化 JSON,我们使用以下代码:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
这将创建 RootObject 的实例,其中包含 Dictionary
访问对象数据
现在,我们可以通过迭代 users 字典,使用各自的键来访问每个子对象:
foreach (string key in root.users.Keys) { User user = root.users[key]; // Access user properties using user.name, user.state, user.id }
以下 C# 代码演示了整个过程:
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); // Iterate over users and print their data foreach (string key in root.users.Keys) { User user = root.users[key]; Console.WriteLine("key: " + 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
以上是如何在 C# 中使用动态键名称反序列化 JSON?的详细内容。更多信息请关注PHP中文网其他相关文章!