使用不同的鍵名稱序列化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中文網其他相關文章!