在处理包含具有动态键的对象的 JSON 数据时,传统的类反序列化可能会带来挑战。本文将探讨如何使用 JSON.NET 来解决这种情况。
考虑以下 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" } } }
我们如何直接访问每个对象根据此数据,无需手动密钥
JSON.NET 提供了一个方便的解决方案,使用其 Dictionary
为了实现这一点,我们定义两个类:
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; } }
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
以上是JSON.NET 如何有效地将带有动态键的 JSON 反序列化为可访问的对象?的详细内容。更多信息请关注PHP中文网其他相关文章!