Using JSON.NET to read a dynamic property name
我正在使用来自返回 JSON 的外部 API 的数据,如下所示。
1 2 3 4 5 6 | { "data": { "4": { "id":"12", "email":"q23rfedsafsadf", "first_name":"lachlan", |
使用 JSON.NET,我如何获得
这是一个有效的 dotNetFiddle:https://dotnetfiddle.net/6Zq5Ry
这是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | using System; using Newtonsoft.Json; using System.Collections.Generic; public class Program { public static void Main() { string json = @"{ 'data': { '4': { 'id': '12', 'email': '[email protected]', 'first_name': 'lachlan' }, '5': { 'id': '15', 'email': '[email protected]', 'first_name': 'appuswamy' } } }"; var data = JsonConvert.DeserializeObject<RootObject>(json); Console.WriteLine("# of items deserialized : {0}", data.DataItems.Count); foreach ( var item in data.DataItems) { Console.WriteLine(" Item Key {0}:", item.Key); Console.WriteLine(" id: {0}", item.Value.id); Console.WriteLine(" email: {0}", item.Value.email); Console.WriteLine(" first_name: {0}", item.Value.first_name); } } } public class RootObject { [JsonProperty(PropertyName ="data")] public Dictionary<string,DataItem> DataItems { get; set; } } public class DataItem { public string id { get; set; } public string email { get; set; } public string first_name { get; set; } } |
这是输出: