在處理包含具有動態鍵的物件的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中文網其他相關文章!